checkout-index: add parallel checkout support
[git/debian.git] / sequencer.c
blobb4c63ae207e32c4579c808c34bf0f8737d85b375
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "exec-cmd.h"
12 #include "utf8.h"
13 #include "cache-tree.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "rerere.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
19 #include "refs.h"
20 #include "strvec.h"
21 #include "quote.h"
22 #include "trailer.h"
23 #include "log-tree.h"
24 #include "wt-status.h"
25 #include "hashmap.h"
26 #include "notes-utils.h"
27 #include "sigchain.h"
28 #include "unpack-trees.h"
29 #include "worktree.h"
30 #include "oidmap.h"
31 #include "oidset.h"
32 #include "commit-slab.h"
33 #include "alias.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
36 #include "reset.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
67 * actions.
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
72 * for the prompt).
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 * being rebased.
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
151 * command-line.
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
168 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
170 static int git_sequencer_config(const char *k, const char *v, void *cb)
172 struct replay_opts *opts = cb;
173 int status;
175 if (!strcmp(k, "commit.cleanup")) {
176 const char *s;
178 status = git_config_string(&s, k, v);
179 if (status)
180 return status;
182 if (!strcmp(s, "verbatim")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "whitespace")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "strip")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
190 opts->explicit_cleanup = 1;
191 } else if (!strcmp(s, "scissors")) {
192 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
193 opts->explicit_cleanup = 1;
194 } else {
195 warning(_("invalid commit message cleanup mode '%s'"),
199 free((char *)s);
200 return status;
203 if (!strcmp(k, "commit.gpgsign")) {
204 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
205 return 0;
208 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
209 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
210 if (ret == 0) {
212 * pull.twohead is allowed to be multi-valued; we only
213 * care about the first value.
215 char *tmp = strchr(opts->default_strategy, ' ');
216 if (tmp)
217 *tmp = '\0';
219 return ret;
222 status = git_gpg_config(k, v, NULL);
223 if (status)
224 return status;
226 return git_diff_basic_config(k, v, NULL);
229 void sequencer_init_config(struct replay_opts *opts)
231 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
232 git_config(git_sequencer_config, opts);
235 static inline int is_rebase_i(const struct replay_opts *opts)
237 return opts->action == REPLAY_INTERACTIVE_REBASE;
240 static const char *get_dir(const struct replay_opts *opts)
242 if (is_rebase_i(opts))
243 return rebase_path();
244 return git_path_seq_dir();
247 static const char *get_todo_path(const struct replay_opts *opts)
249 if (is_rebase_i(opts))
250 return rebase_path_todo();
251 return git_path_todo_file();
255 * Returns 0 for non-conforming footer
256 * Returns 1 for conforming footer
257 * Returns 2 when sob exists within conforming footer
258 * Returns 3 when sob exists within conforming footer as last entry
260 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
261 size_t ignore_footer)
263 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
264 struct trailer_info info;
265 size_t i;
266 int found_sob = 0, found_sob_last = 0;
267 char saved_char;
269 opts.no_divider = 1;
271 if (ignore_footer) {
272 saved_char = sb->buf[sb->len - ignore_footer];
273 sb->buf[sb->len - ignore_footer] = '\0';
276 trailer_info_get(&info, sb->buf, &opts);
278 if (ignore_footer)
279 sb->buf[sb->len - ignore_footer] = saved_char;
281 if (info.trailer_start == info.trailer_end)
282 return 0;
284 for (i = 0; i < info.trailer_nr; i++)
285 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
286 found_sob = 1;
287 if (i == info.trailer_nr - 1)
288 found_sob_last = 1;
291 trailer_info_release(&info);
293 if (found_sob_last)
294 return 3;
295 if (found_sob)
296 return 2;
297 return 1;
300 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
302 static struct strbuf buf = STRBUF_INIT;
304 strbuf_reset(&buf);
305 if (opts->gpg_sign)
306 sq_quotef(&buf, "-S%s", opts->gpg_sign);
307 return buf.buf;
310 int sequencer_remove_state(struct replay_opts *opts)
312 struct strbuf buf = STRBUF_INIT;
313 int i, ret = 0;
315 if (is_rebase_i(opts) &&
316 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
317 char *p = buf.buf;
318 while (*p) {
319 char *eol = strchr(p, '\n');
320 if (eol)
321 *eol = '\0';
322 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
323 warning(_("could not delete '%s'"), p);
324 ret = -1;
326 if (!eol)
327 break;
328 p = eol + 1;
332 free(opts->gpg_sign);
333 free(opts->default_strategy);
334 free(opts->strategy);
335 for (i = 0; i < opts->xopts_nr; i++)
336 free(opts->xopts[i]);
337 free(opts->xopts);
338 strbuf_release(&opts->current_fixups);
340 strbuf_reset(&buf);
341 strbuf_addstr(&buf, get_dir(opts));
342 if (remove_dir_recursively(&buf, 0))
343 ret = error(_("could not remove '%s'"), buf.buf);
344 strbuf_release(&buf);
346 return ret;
349 static const char *action_name(const struct replay_opts *opts)
351 switch (opts->action) {
352 case REPLAY_REVERT:
353 return N_("revert");
354 case REPLAY_PICK:
355 return N_("cherry-pick");
356 case REPLAY_INTERACTIVE_REBASE:
357 return N_("rebase");
359 die(_("unknown action: %d"), opts->action);
362 struct commit_message {
363 char *parent_label;
364 char *label;
365 char *subject;
366 const char *message;
369 static const char *short_commit_name(struct commit *commit)
371 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
374 static int get_message(struct commit *commit, struct commit_message *out)
376 const char *abbrev, *subject;
377 int subject_len;
379 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
380 abbrev = short_commit_name(commit);
382 subject_len = find_commit_subject(out->message, &subject);
384 out->subject = xmemdupz(subject, subject_len);
385 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
386 out->parent_label = xstrfmt("parent of %s", out->label);
388 return 0;
391 static void free_message(struct commit *commit, struct commit_message *msg)
393 free(msg->parent_label);
394 free(msg->label);
395 free(msg->subject);
396 unuse_commit_buffer(commit, msg->message);
399 static void print_advice(struct repository *r, int show_hint,
400 struct replay_opts *opts)
402 char *msg = getenv("GIT_CHERRY_PICK_HELP");
404 if (msg) {
405 fprintf(stderr, "%s\n", msg);
407 * A conflict has occurred but the porcelain
408 * (typically rebase --interactive) wants to take care
409 * of the commit itself so remove CHERRY_PICK_HEAD
411 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
412 NULL, 0);
413 return;
416 if (show_hint) {
417 if (opts->no_commit)
418 advise(_("after resolving the conflicts, mark the corrected paths\n"
419 "with 'git add <paths>' or 'git rm <paths>'"));
420 else
421 advise(_("after resolving the conflicts, mark the corrected paths\n"
422 "with 'git add <paths>' or 'git rm <paths>'\n"
423 "and commit the result with 'git commit'"));
427 static int write_message(const void *buf, size_t len, const char *filename,
428 int append_eol)
430 struct lock_file msg_file = LOCK_INIT;
432 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
433 if (msg_fd < 0)
434 return error_errno(_("could not lock '%s'"), filename);
435 if (write_in_full(msg_fd, buf, len) < 0) {
436 error_errno(_("could not write to '%s'"), filename);
437 rollback_lock_file(&msg_file);
438 return -1;
440 if (append_eol && write(msg_fd, "\n", 1) < 0) {
441 error_errno(_("could not write eol to '%s'"), filename);
442 rollback_lock_file(&msg_file);
443 return -1;
445 if (commit_lock_file(&msg_file) < 0)
446 return error(_("failed to finalize '%s'"), filename);
448 return 0;
451 int read_oneliner(struct strbuf *buf,
452 const char *path, unsigned flags)
454 int orig_len = buf->len;
456 if (strbuf_read_file(buf, path, 0) < 0) {
457 if ((flags & READ_ONELINER_WARN_MISSING) ||
458 (errno != ENOENT && errno != ENOTDIR))
459 warning_errno(_("could not read '%s'"), path);
460 return 0;
463 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
464 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
465 --buf->len;
466 buf->buf[buf->len] = '\0';
469 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
470 return 0;
472 return 1;
475 static struct tree *empty_tree(struct repository *r)
477 return lookup_tree(r, the_hash_algo->empty_tree);
480 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
482 if (repo_read_index_unmerged(repo))
483 return error_resolve_conflict(_(action_name(opts)));
485 error(_("your local changes would be overwritten by %s."),
486 _(action_name(opts)));
488 if (advice_commit_before_merge)
489 advise(_("commit your changes or stash them to proceed."));
490 return -1;
493 static void update_abort_safety_file(void)
495 struct object_id head;
497 /* Do nothing on a single-pick */
498 if (!file_exists(git_path_seq_dir()))
499 return;
501 if (!get_oid("HEAD", &head))
502 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
503 else
504 write_file(git_path_abort_safety_file(), "%s", "");
507 static int fast_forward_to(struct repository *r,
508 const struct object_id *to,
509 const struct object_id *from,
510 int unborn,
511 struct replay_opts *opts)
513 struct ref_transaction *transaction;
514 struct strbuf sb = STRBUF_INIT;
515 struct strbuf err = STRBUF_INIT;
517 repo_read_index(r);
518 if (checkout_fast_forward(r, from, to, 1))
519 return -1; /* the callee should have complained already */
521 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
523 transaction = ref_transaction_begin(&err);
524 if (!transaction ||
525 ref_transaction_update(transaction, "HEAD",
526 to, unborn && !is_rebase_i(opts) ?
527 &null_oid : from,
528 0, sb.buf, &err) ||
529 ref_transaction_commit(transaction, &err)) {
530 ref_transaction_free(transaction);
531 error("%s", err.buf);
532 strbuf_release(&sb);
533 strbuf_release(&err);
534 return -1;
537 strbuf_release(&sb);
538 strbuf_release(&err);
539 ref_transaction_free(transaction);
540 update_abort_safety_file();
541 return 0;
544 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
545 int use_editor)
547 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
548 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
549 COMMIT_MSG_CLEANUP_SPACE;
550 else if (!strcmp(cleanup_arg, "verbatim"))
551 return COMMIT_MSG_CLEANUP_NONE;
552 else if (!strcmp(cleanup_arg, "whitespace"))
553 return COMMIT_MSG_CLEANUP_SPACE;
554 else if (!strcmp(cleanup_arg, "strip"))
555 return COMMIT_MSG_CLEANUP_ALL;
556 else if (!strcmp(cleanup_arg, "scissors"))
557 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
558 COMMIT_MSG_CLEANUP_SPACE;
559 else
560 die(_("Invalid cleanup mode %s"), cleanup_arg);
564 * NB using int rather than enum cleanup_mode to stop clang's
565 * -Wtautological-constant-out-of-range-compare complaining that the comparison
566 * is always true.
568 static const char *describe_cleanup_mode(int cleanup_mode)
570 static const char *modes[] = { "whitespace",
571 "verbatim",
572 "scissors",
573 "strip" };
575 if (cleanup_mode < ARRAY_SIZE(modes))
576 return modes[cleanup_mode];
578 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
581 void append_conflicts_hint(struct index_state *istate,
582 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
584 int i;
586 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
587 strbuf_addch(msgbuf, '\n');
588 wt_status_append_cut_line(msgbuf);
589 strbuf_addch(msgbuf, comment_line_char);
592 strbuf_addch(msgbuf, '\n');
593 strbuf_commented_addf(msgbuf, "Conflicts:\n");
594 for (i = 0; i < istate->cache_nr;) {
595 const struct cache_entry *ce = istate->cache[i++];
596 if (ce_stage(ce)) {
597 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
598 while (i < istate->cache_nr &&
599 !strcmp(ce->name, istate->cache[i]->name))
600 i++;
605 static int do_recursive_merge(struct repository *r,
606 struct commit *base, struct commit *next,
607 const char *base_label, const char *next_label,
608 struct object_id *head, struct strbuf *msgbuf,
609 struct replay_opts *opts)
611 struct merge_options o;
612 struct merge_result result;
613 struct tree *next_tree, *base_tree, *head_tree;
614 int clean, show_output;
615 int i;
616 struct lock_file index_lock = LOCK_INIT;
618 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
619 return -1;
621 repo_read_index(r);
623 init_merge_options(&o, r);
624 o.ancestor = base ? base_label : "(empty tree)";
625 o.branch1 = "HEAD";
626 o.branch2 = next ? next_label : "(empty tree)";
627 if (is_rebase_i(opts))
628 o.buffer_output = 2;
629 o.show_rename_progress = 1;
631 head_tree = parse_tree_indirect(head);
632 next_tree = next ? get_commit_tree(next) : empty_tree(r);
633 base_tree = base ? get_commit_tree(base) : empty_tree(r);
635 for (i = 0; i < opts->xopts_nr; i++)
636 parse_merge_opt(&o, opts->xopts[i]);
638 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
639 memset(&result, 0, sizeof(result));
640 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
641 &result);
642 show_output = !is_rebase_i(opts) || !result.clean;
644 * TODO: merge_switch_to_result will update index/working tree;
645 * we only really want to do that if !result.clean || this is
646 * the final patch to be picked. But determining this is the
647 * final patch would take some work, and "head_tree" would need
648 * to be replace with the tree the index matched before we
649 * started doing any picks.
651 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
652 clean = result.clean;
653 } else {
654 clean = merge_trees(&o, head_tree, next_tree, base_tree);
655 if (is_rebase_i(opts) && clean <= 0)
656 fputs(o.obuf.buf, stdout);
657 strbuf_release(&o.obuf);
659 if (clean < 0) {
660 rollback_lock_file(&index_lock);
661 return clean;
664 if (write_locked_index(r->index, &index_lock,
665 COMMIT_LOCK | SKIP_IF_UNCHANGED))
667 * TRANSLATORS: %s will be "revert", "cherry-pick" or
668 * "rebase".
670 return error(_("%s: Unable to write new index file"),
671 _(action_name(opts)));
673 if (!clean)
674 append_conflicts_hint(r->index, msgbuf,
675 opts->default_msg_cleanup);
677 return !clean;
680 static struct object_id *get_cache_tree_oid(struct index_state *istate)
682 if (!cache_tree_fully_valid(istate->cache_tree))
683 if (cache_tree_update(istate, 0)) {
684 error(_("unable to update cache tree"));
685 return NULL;
688 return &istate->cache_tree->oid;
691 static int is_index_unchanged(struct repository *r)
693 struct object_id head_oid, *cache_tree_oid;
694 struct commit *head_commit;
695 struct index_state *istate = r->index;
697 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
698 return error(_("could not resolve HEAD commit"));
700 head_commit = lookup_commit(r, &head_oid);
703 * If head_commit is NULL, check_commit, called from
704 * lookup_commit, would have indicated that head_commit is not
705 * a commit object already. parse_commit() will return failure
706 * without further complaints in such a case. Otherwise, if
707 * the commit is invalid, parse_commit() will complain. So
708 * there is nothing for us to say here. Just return failure.
710 if (parse_commit(head_commit))
711 return -1;
713 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
714 return -1;
716 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
719 static int write_author_script(const char *message)
721 struct strbuf buf = STRBUF_INIT;
722 const char *eol;
723 int res;
725 for (;;)
726 if (!*message || starts_with(message, "\n")) {
727 missing_author:
728 /* Missing 'author' line? */
729 unlink(rebase_path_author_script());
730 return 0;
731 } else if (skip_prefix(message, "author ", &message))
732 break;
733 else if ((eol = strchr(message, '\n')))
734 message = eol + 1;
735 else
736 goto missing_author;
738 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
739 while (*message && *message != '\n' && *message != '\r')
740 if (skip_prefix(message, " <", &message))
741 break;
742 else if (*message != '\'')
743 strbuf_addch(&buf, *(message++));
744 else
745 strbuf_addf(&buf, "'\\%c'", *(message++));
746 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
747 while (*message && *message != '\n' && *message != '\r')
748 if (skip_prefix(message, "> ", &message))
749 break;
750 else if (*message != '\'')
751 strbuf_addch(&buf, *(message++));
752 else
753 strbuf_addf(&buf, "'\\%c'", *(message++));
754 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
755 while (*message && *message != '\n' && *message != '\r')
756 if (*message != '\'')
757 strbuf_addch(&buf, *(message++));
758 else
759 strbuf_addf(&buf, "'\\%c'", *(message++));
760 strbuf_addch(&buf, '\'');
761 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
762 strbuf_release(&buf);
763 return res;
767 * Take a series of KEY='VALUE' lines where VALUE part is
768 * sq-quoted, and append <KEY, VALUE> at the end of the string list
770 static int parse_key_value_squoted(char *buf, struct string_list *list)
772 while (*buf) {
773 struct string_list_item *item;
774 char *np;
775 char *cp = strchr(buf, '=');
776 if (!cp) {
777 np = strchrnul(buf, '\n');
778 return error(_("no key present in '%.*s'"),
779 (int) (np - buf), buf);
781 np = strchrnul(cp, '\n');
782 *cp++ = '\0';
783 item = string_list_append(list, buf);
785 buf = np + (*np == '\n');
786 *np = '\0';
787 cp = sq_dequote(cp);
788 if (!cp)
789 return error(_("unable to dequote value of '%s'"),
790 item->string);
791 item->util = xstrdup(cp);
793 return 0;
797 * Reads and parses the state directory's "author-script" file, and sets name,
798 * email and date accordingly.
799 * Returns 0 on success, -1 if the file could not be parsed.
801 * The author script is of the format:
803 * GIT_AUTHOR_NAME='$author_name'
804 * GIT_AUTHOR_EMAIL='$author_email'
805 * GIT_AUTHOR_DATE='$author_date'
807 * where $author_name, $author_email and $author_date are quoted. We are strict
808 * with our parsing, as the file was meant to be eval'd in the now-removed
809 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
810 * from what this function expects, it is better to bail out than to do
811 * something that the user does not expect.
813 int read_author_script(const char *path, char **name, char **email, char **date,
814 int allow_missing)
816 struct strbuf buf = STRBUF_INIT;
817 struct string_list kv = STRING_LIST_INIT_DUP;
818 int retval = -1; /* assume failure */
819 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
821 if (strbuf_read_file(&buf, path, 256) <= 0) {
822 strbuf_release(&buf);
823 if (errno == ENOENT && allow_missing)
824 return 0;
825 else
826 return error_errno(_("could not open '%s' for reading"),
827 path);
830 if (parse_key_value_squoted(buf.buf, &kv))
831 goto finish;
833 for (i = 0; i < kv.nr; i++) {
834 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
835 if (name_i != -2)
836 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
837 else
838 name_i = i;
839 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
840 if (email_i != -2)
841 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
842 else
843 email_i = i;
844 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
845 if (date_i != -2)
846 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
847 else
848 date_i = i;
849 } else {
850 err = error(_("unknown variable '%s'"),
851 kv.items[i].string);
854 if (name_i == -2)
855 error(_("missing 'GIT_AUTHOR_NAME'"));
856 if (email_i == -2)
857 error(_("missing 'GIT_AUTHOR_EMAIL'"));
858 if (date_i == -2)
859 error(_("missing 'GIT_AUTHOR_DATE'"));
860 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
861 goto finish;
862 *name = kv.items[name_i].util;
863 *email = kv.items[email_i].util;
864 *date = kv.items[date_i].util;
865 retval = 0;
866 finish:
867 string_list_clear(&kv, !!retval);
868 strbuf_release(&buf);
869 return retval;
873 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
874 * file with shell quoting into struct strvec. Returns -1 on
875 * error, 0 otherwise.
877 static int read_env_script(struct strvec *env)
879 char *name, *email, *date;
881 if (read_author_script(rebase_path_author_script(),
882 &name, &email, &date, 0))
883 return -1;
885 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
886 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
887 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
888 free(name);
889 free(email);
890 free(date);
892 return 0;
895 static char *get_author(const char *message)
897 size_t len;
898 const char *a;
900 a = find_commit_header(message, "author", &len);
901 if (a)
902 return xmemdupz(a, len);
904 return NULL;
907 static const char *author_date_from_env_array(const struct strvec *env)
909 int i;
910 const char *date;
912 for (i = 0; i < env->nr; i++)
913 if (skip_prefix(env->v[i],
914 "GIT_AUTHOR_DATE=", &date))
915 return date;
917 * If GIT_AUTHOR_DATE is missing we should have already errored out when
918 * reading the script
920 BUG("GIT_AUTHOR_DATE missing from author script");
923 static const char staged_changes_advice[] =
924 N_("you have staged changes in your working tree\n"
925 "If these changes are meant to be squashed into the previous commit, run:\n"
926 "\n"
927 " git commit --amend %s\n"
928 "\n"
929 "If they are meant to go into a new commit, run:\n"
930 "\n"
931 " git commit %s\n"
932 "\n"
933 "In both cases, once you're done, continue with:\n"
934 "\n"
935 " git rebase --continue\n");
937 #define ALLOW_EMPTY (1<<0)
938 #define EDIT_MSG (1<<1)
939 #define AMEND_MSG (1<<2)
940 #define CLEANUP_MSG (1<<3)
941 #define VERIFY_MSG (1<<4)
942 #define CREATE_ROOT_COMMIT (1<<5)
943 #define VERBATIM_MSG (1<<6)
945 static int run_command_silent_on_success(struct child_process *cmd)
947 struct strbuf buf = STRBUF_INIT;
948 int rc;
950 cmd->stdout_to_stderr = 1;
951 rc = pipe_command(cmd,
952 NULL, 0,
953 NULL, 0,
954 &buf, 0);
956 if (rc)
957 fputs(buf.buf, stderr);
958 strbuf_release(&buf);
959 return rc;
963 * If we are cherry-pick, and if the merge did not result in
964 * hand-editing, we will hit this commit and inherit the original
965 * author date and name.
967 * If we are revert, or if our cherry-pick results in a hand merge,
968 * we had better say that the current user is responsible for that.
970 * An exception is when run_git_commit() is called during an
971 * interactive rebase: in that case, we will want to retain the
972 * author metadata.
974 static int run_git_commit(const char *defmsg,
975 struct replay_opts *opts,
976 unsigned int flags)
978 struct child_process cmd = CHILD_PROCESS_INIT;
980 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
981 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
983 cmd.git_cmd = 1;
985 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
986 const char *gpg_opt = gpg_sign_opt_quoted(opts);
988 return error(_(staged_changes_advice),
989 gpg_opt, gpg_opt);
992 if (opts->committer_date_is_author_date)
993 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
994 opts->ignore_date ?
995 "" :
996 author_date_from_env_array(&cmd.env_array));
997 if (opts->ignore_date)
998 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1000 strvec_push(&cmd.args, "commit");
1002 if (!(flags & VERIFY_MSG))
1003 strvec_push(&cmd.args, "-n");
1004 if ((flags & AMEND_MSG))
1005 strvec_push(&cmd.args, "--amend");
1006 if (opts->gpg_sign)
1007 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1008 else
1009 strvec_push(&cmd.args, "--no-gpg-sign");
1010 if (defmsg)
1011 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1012 else if (!(flags & EDIT_MSG))
1013 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1014 if ((flags & CLEANUP_MSG))
1015 strvec_push(&cmd.args, "--cleanup=strip");
1016 if ((flags & VERBATIM_MSG))
1017 strvec_push(&cmd.args, "--cleanup=verbatim");
1018 if ((flags & EDIT_MSG))
1019 strvec_push(&cmd.args, "-e");
1020 else if (!(flags & CLEANUP_MSG) &&
1021 !opts->signoff && !opts->record_origin &&
1022 !opts->explicit_cleanup)
1023 strvec_push(&cmd.args, "--cleanup=verbatim");
1025 if ((flags & ALLOW_EMPTY))
1026 strvec_push(&cmd.args, "--allow-empty");
1028 if (!(flags & EDIT_MSG))
1029 strvec_push(&cmd.args, "--allow-empty-message");
1031 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1032 return run_command_silent_on_success(&cmd);
1033 else
1034 return run_command(&cmd);
1037 static int rest_is_empty(const struct strbuf *sb, int start)
1039 int i, eol;
1040 const char *nl;
1042 /* Check if the rest is just whitespace and Signed-off-by's. */
1043 for (i = start; i < sb->len; i++) {
1044 nl = memchr(sb->buf + i, '\n', sb->len - i);
1045 if (nl)
1046 eol = nl - sb->buf;
1047 else
1048 eol = sb->len;
1050 if (strlen(sign_off_header) <= eol - i &&
1051 starts_with(sb->buf + i, sign_off_header)) {
1052 i = eol;
1053 continue;
1055 while (i < eol)
1056 if (!isspace(sb->buf[i++]))
1057 return 0;
1060 return 1;
1063 void cleanup_message(struct strbuf *msgbuf,
1064 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1066 if (verbose || /* Truncate the message just before the diff, if any. */
1067 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1068 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1069 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1070 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1074 * Find out if the message in the strbuf contains only whitespace and
1075 * Signed-off-by lines.
1077 int message_is_empty(const struct strbuf *sb,
1078 enum commit_msg_cleanup_mode cleanup_mode)
1080 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1081 return 0;
1082 return rest_is_empty(sb, 0);
1086 * See if the user edited the message in the editor or left what
1087 * was in the template intact
1089 int template_untouched(const struct strbuf *sb, const char *template_file,
1090 enum commit_msg_cleanup_mode cleanup_mode)
1092 struct strbuf tmpl = STRBUF_INIT;
1093 const char *start;
1095 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1096 return 0;
1098 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1099 return 0;
1101 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1102 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1103 start = sb->buf;
1104 strbuf_release(&tmpl);
1105 return rest_is_empty(sb, start - sb->buf);
1108 int update_head_with_reflog(const struct commit *old_head,
1109 const struct object_id *new_head,
1110 const char *action, const struct strbuf *msg,
1111 struct strbuf *err)
1113 struct ref_transaction *transaction;
1114 struct strbuf sb = STRBUF_INIT;
1115 const char *nl;
1116 int ret = 0;
1118 if (action) {
1119 strbuf_addstr(&sb, action);
1120 strbuf_addstr(&sb, ": ");
1123 nl = strchr(msg->buf, '\n');
1124 if (nl) {
1125 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1126 } else {
1127 strbuf_addbuf(&sb, msg);
1128 strbuf_addch(&sb, '\n');
1131 transaction = ref_transaction_begin(err);
1132 if (!transaction ||
1133 ref_transaction_update(transaction, "HEAD", new_head,
1134 old_head ? &old_head->object.oid : &null_oid,
1135 0, sb.buf, err) ||
1136 ref_transaction_commit(transaction, err)) {
1137 ret = -1;
1139 ref_transaction_free(transaction);
1140 strbuf_release(&sb);
1142 return ret;
1145 static int run_rewrite_hook(const struct object_id *oldoid,
1146 const struct object_id *newoid)
1148 struct child_process proc = CHILD_PROCESS_INIT;
1149 const char *argv[3];
1150 int code;
1151 struct strbuf sb = STRBUF_INIT;
1153 argv[0] = find_hook("post-rewrite");
1154 if (!argv[0])
1155 return 0;
1157 argv[1] = "amend";
1158 argv[2] = NULL;
1160 proc.argv = argv;
1161 proc.in = -1;
1162 proc.stdout_to_stderr = 1;
1163 proc.trace2_hook_name = "post-rewrite";
1165 code = start_command(&proc);
1166 if (code)
1167 return code;
1168 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1169 sigchain_push(SIGPIPE, SIG_IGN);
1170 write_in_full(proc.in, sb.buf, sb.len);
1171 close(proc.in);
1172 strbuf_release(&sb);
1173 sigchain_pop(SIGPIPE);
1174 return finish_command(&proc);
1177 void commit_post_rewrite(struct repository *r,
1178 const struct commit *old_head,
1179 const struct object_id *new_head)
1181 struct notes_rewrite_cfg *cfg;
1183 cfg = init_copy_notes_for_rewrite("amend");
1184 if (cfg) {
1185 /* we are amending, so old_head is not NULL */
1186 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1187 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1189 run_rewrite_hook(&old_head->object.oid, new_head);
1192 static int run_prepare_commit_msg_hook(struct repository *r,
1193 struct strbuf *msg,
1194 const char *commit)
1196 int ret = 0;
1197 const char *name, *arg1 = NULL, *arg2 = NULL;
1199 name = git_path_commit_editmsg();
1200 if (write_message(msg->buf, msg->len, name, 0))
1201 return -1;
1203 if (commit) {
1204 arg1 = "commit";
1205 arg2 = commit;
1206 } else {
1207 arg1 = "message";
1209 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1210 arg1, arg2, NULL))
1211 ret = error(_("'prepare-commit-msg' hook failed"));
1213 return ret;
1216 static const char implicit_ident_advice_noconfig[] =
1217 N_("Your name and email address were configured automatically based\n"
1218 "on your username and hostname. Please check that they are accurate.\n"
1219 "You can suppress this message by setting them explicitly. Run the\n"
1220 "following command and follow the instructions in your editor to edit\n"
1221 "your configuration file:\n"
1222 "\n"
1223 " git config --global --edit\n"
1224 "\n"
1225 "After doing this, you may fix the identity used for this commit with:\n"
1226 "\n"
1227 " git commit --amend --reset-author\n");
1229 static const char implicit_ident_advice_config[] =
1230 N_("Your name and email address were configured automatically based\n"
1231 "on your username and hostname. Please check that they are accurate.\n"
1232 "You can suppress this message by setting them explicitly:\n"
1233 "\n"
1234 " git config --global user.name \"Your Name\"\n"
1235 " git config --global user.email you@example.com\n"
1236 "\n"
1237 "After doing this, you may fix the identity used for this commit with:\n"
1238 "\n"
1239 " git commit --amend --reset-author\n");
1241 static const char *implicit_ident_advice(void)
1243 char *user_config = expand_user_path("~/.gitconfig", 0);
1244 char *xdg_config = xdg_config_home("config");
1245 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1247 free(user_config);
1248 free(xdg_config);
1250 if (config_exists)
1251 return _(implicit_ident_advice_config);
1252 else
1253 return _(implicit_ident_advice_noconfig);
1257 void print_commit_summary(struct repository *r,
1258 const char *prefix,
1259 const struct object_id *oid,
1260 unsigned int flags)
1262 struct rev_info rev;
1263 struct commit *commit;
1264 struct strbuf format = STRBUF_INIT;
1265 const char *head;
1266 struct pretty_print_context pctx = {0};
1267 struct strbuf author_ident = STRBUF_INIT;
1268 struct strbuf committer_ident = STRBUF_INIT;
1270 commit = lookup_commit(r, oid);
1271 if (!commit)
1272 die(_("couldn't look up newly created commit"));
1273 if (parse_commit(commit))
1274 die(_("could not parse newly created commit"));
1276 strbuf_addstr(&format, "format:%h] %s");
1278 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1279 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1280 if (strbuf_cmp(&author_ident, &committer_ident)) {
1281 strbuf_addstr(&format, "\n Author: ");
1282 strbuf_addbuf_percentquote(&format, &author_ident);
1284 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1285 struct strbuf date = STRBUF_INIT;
1287 format_commit_message(commit, "%ad", &date, &pctx);
1288 strbuf_addstr(&format, "\n Date: ");
1289 strbuf_addbuf_percentquote(&format, &date);
1290 strbuf_release(&date);
1292 if (!committer_ident_sufficiently_given()) {
1293 strbuf_addstr(&format, "\n Committer: ");
1294 strbuf_addbuf_percentquote(&format, &committer_ident);
1295 if (advice_implicit_identity) {
1296 strbuf_addch(&format, '\n');
1297 strbuf_addstr(&format, implicit_ident_advice());
1300 strbuf_release(&author_ident);
1301 strbuf_release(&committer_ident);
1303 repo_init_revisions(r, &rev, prefix);
1304 setup_revisions(0, NULL, &rev, NULL);
1306 rev.diff = 1;
1307 rev.diffopt.output_format =
1308 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1310 rev.verbose_header = 1;
1311 rev.show_root_diff = 1;
1312 get_commit_format(format.buf, &rev);
1313 rev.always_show_header = 0;
1314 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1315 rev.diffopt.break_opt = 0;
1316 diff_setup_done(&rev.diffopt);
1318 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1319 if (!head)
1320 die_errno(_("unable to resolve HEAD after creating commit"));
1321 if (!strcmp(head, "HEAD"))
1322 head = _("detached HEAD");
1323 else
1324 skip_prefix(head, "refs/heads/", &head);
1325 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1326 _(" (root-commit)") : "");
1328 if (!log_tree_commit(&rev, commit)) {
1329 rev.always_show_header = 1;
1330 rev.use_terminator = 1;
1331 log_tree_commit(&rev, commit);
1334 strbuf_release(&format);
1337 static int parse_head(struct repository *r, struct commit **head)
1339 struct commit *current_head;
1340 struct object_id oid;
1342 if (get_oid("HEAD", &oid)) {
1343 current_head = NULL;
1344 } else {
1345 current_head = lookup_commit_reference(r, &oid);
1346 if (!current_head)
1347 return error(_("could not parse HEAD"));
1348 if (!oideq(&oid, &current_head->object.oid)) {
1349 warning(_("HEAD %s is not a commit!"),
1350 oid_to_hex(&oid));
1352 if (parse_commit(current_head))
1353 return error(_("could not parse HEAD commit"));
1355 *head = current_head;
1357 return 0;
1361 * Try to commit without forking 'git commit'. In some cases we need
1362 * to run 'git commit' to display an error message
1364 * Returns:
1365 * -1 - error unable to commit
1366 * 0 - success
1367 * 1 - run 'git commit'
1369 static int try_to_commit(struct repository *r,
1370 struct strbuf *msg, const char *author,
1371 struct replay_opts *opts, unsigned int flags,
1372 struct object_id *oid)
1374 struct object_id tree;
1375 struct commit *current_head = NULL;
1376 struct commit_list *parents = NULL;
1377 struct commit_extra_header *extra = NULL;
1378 struct strbuf err = STRBUF_INIT;
1379 struct strbuf commit_msg = STRBUF_INIT;
1380 char *amend_author = NULL;
1381 const char *committer = NULL;
1382 const char *hook_commit = NULL;
1383 enum commit_msg_cleanup_mode cleanup;
1384 int res = 0;
1386 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1387 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1389 if (parse_head(r, &current_head))
1390 return -1;
1392 if (flags & AMEND_MSG) {
1393 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1394 const char *out_enc = get_commit_output_encoding();
1395 const char *message = logmsg_reencode(current_head, NULL,
1396 out_enc);
1398 if (!msg) {
1399 const char *orig_message = NULL;
1401 find_commit_subject(message, &orig_message);
1402 msg = &commit_msg;
1403 strbuf_addstr(msg, orig_message);
1404 hook_commit = "HEAD";
1406 author = amend_author = get_author(message);
1407 unuse_commit_buffer(current_head, message);
1408 if (!author) {
1409 res = error(_("unable to parse commit author"));
1410 goto out;
1412 parents = copy_commit_list(current_head->parents);
1413 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1414 } else if (current_head &&
1415 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1416 commit_list_insert(current_head, &parents);
1419 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1420 res = error(_("git write-tree failed to write a tree"));
1421 goto out;
1424 if (!(flags & ALLOW_EMPTY)) {
1425 struct commit *first_parent = current_head;
1427 if (flags & AMEND_MSG) {
1428 if (current_head->parents) {
1429 first_parent = current_head->parents->item;
1430 if (repo_parse_commit(r, first_parent)) {
1431 res = error(_("could not parse HEAD commit"));
1432 goto out;
1434 } else {
1435 first_parent = NULL;
1438 if (oideq(first_parent
1439 ? get_commit_tree_oid(first_parent)
1440 : the_hash_algo->empty_tree,
1441 &tree)) {
1442 res = 1; /* run 'git commit' to display error message */
1443 goto out;
1447 if (find_hook("prepare-commit-msg")) {
1448 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1449 if (res)
1450 goto out;
1451 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1452 2048) < 0) {
1453 res = error_errno(_("unable to read commit message "
1454 "from '%s'"),
1455 git_path_commit_editmsg());
1456 goto out;
1458 msg = &commit_msg;
1461 if (flags & CLEANUP_MSG)
1462 cleanup = COMMIT_MSG_CLEANUP_ALL;
1463 else if (flags & VERBATIM_MSG)
1464 cleanup = COMMIT_MSG_CLEANUP_NONE;
1465 else if ((opts->signoff || opts->record_origin) &&
1466 !opts->explicit_cleanup)
1467 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1468 else
1469 cleanup = opts->default_msg_cleanup;
1471 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1472 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1473 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1474 res = 1; /* run 'git commit' to display error message */
1475 goto out;
1478 if (opts->committer_date_is_author_date) {
1479 struct ident_split id;
1480 struct strbuf date = STRBUF_INIT;
1482 if (!opts->ignore_date) {
1483 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1484 res = error(_("invalid author identity '%s'"),
1485 author);
1486 goto out;
1488 if (!id.date_begin) {
1489 res = error(_(
1490 "corrupt author: missing date information"));
1491 goto out;
1493 strbuf_addf(&date, "@%.*s %.*s",
1494 (int)(id.date_end - id.date_begin),
1495 id.date_begin,
1496 (int)(id.tz_end - id.tz_begin),
1497 id.tz_begin);
1498 } else {
1499 reset_ident_date();
1501 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1502 getenv("GIT_COMMITTER_EMAIL"),
1503 WANT_COMMITTER_IDENT,
1504 opts->ignore_date ? NULL : date.buf,
1505 IDENT_STRICT);
1506 strbuf_release(&date);
1507 } else {
1508 reset_ident_date();
1511 if (opts->ignore_date) {
1512 struct ident_split id;
1513 char *name, *email;
1515 if (split_ident_line(&id, author, strlen(author)) < 0) {
1516 error(_("invalid author identity '%s'"), author);
1517 goto out;
1519 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1520 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1521 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1522 IDENT_STRICT);
1523 free(name);
1524 free(email);
1527 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1528 author, committer, opts->gpg_sign, extra)) {
1529 res = error(_("failed to write commit object"));
1530 goto out;
1533 if (update_head_with_reflog(current_head, oid,
1534 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1535 res = error("%s", err.buf);
1536 goto out;
1539 run_commit_hook(0, r->index_file, "post-commit", NULL);
1540 if (flags & AMEND_MSG)
1541 commit_post_rewrite(r, current_head, oid);
1543 out:
1544 free_commit_extra_headers(extra);
1545 strbuf_release(&err);
1546 strbuf_release(&commit_msg);
1547 free(amend_author);
1549 return res;
1552 static int write_rebase_head(struct object_id *oid)
1554 if (update_ref("rebase", "REBASE_HEAD", oid,
1555 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1556 return error(_("could not update %s"), "REBASE_HEAD");
1558 return 0;
1561 static int do_commit(struct repository *r,
1562 const char *msg_file, const char *author,
1563 struct replay_opts *opts, unsigned int flags,
1564 struct object_id *oid)
1566 int res = 1;
1568 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1569 struct object_id oid;
1570 struct strbuf sb = STRBUF_INIT;
1572 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1573 return error_errno(_("unable to read commit message "
1574 "from '%s'"),
1575 msg_file);
1577 res = try_to_commit(r, msg_file ? &sb : NULL,
1578 author, opts, flags, &oid);
1579 strbuf_release(&sb);
1580 if (!res) {
1581 refs_delete_ref(get_main_ref_store(r), "",
1582 "CHERRY_PICK_HEAD", NULL, 0);
1583 unlink(git_path_merge_msg(r));
1584 if (!is_rebase_i(opts))
1585 print_commit_summary(r, NULL, &oid,
1586 SUMMARY_SHOW_AUTHOR_DATE);
1587 return res;
1590 if (res == 1) {
1591 if (is_rebase_i(opts) && oid)
1592 if (write_rebase_head(oid))
1593 return -1;
1594 return run_git_commit(msg_file, opts, flags);
1597 return res;
1600 static int is_original_commit_empty(struct commit *commit)
1602 const struct object_id *ptree_oid;
1604 if (parse_commit(commit))
1605 return error(_("could not parse commit %s"),
1606 oid_to_hex(&commit->object.oid));
1607 if (commit->parents) {
1608 struct commit *parent = commit->parents->item;
1609 if (parse_commit(parent))
1610 return error(_("could not parse parent commit %s"),
1611 oid_to_hex(&parent->object.oid));
1612 ptree_oid = get_commit_tree_oid(parent);
1613 } else {
1614 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1617 return oideq(ptree_oid, get_commit_tree_oid(commit));
1621 * Should empty commits be allowed? Return status:
1622 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1623 * 0: Halt on empty commit
1624 * 1: Allow empty commit
1625 * 2: Drop empty commit
1627 static int allow_empty(struct repository *r,
1628 struct replay_opts *opts,
1629 struct commit *commit)
1631 int index_unchanged, originally_empty;
1634 * Four cases:
1636 * (1) we do not allow empty at all and error out.
1638 * (2) we allow ones that were initially empty, and
1639 * just drop the ones that become empty
1641 * (3) we allow ones that were initially empty, but
1642 * halt for the ones that become empty;
1644 * (4) we allow both.
1646 if (!opts->allow_empty)
1647 return 0; /* let "git commit" barf as necessary */
1649 index_unchanged = is_index_unchanged(r);
1650 if (index_unchanged < 0)
1651 return index_unchanged;
1652 if (!index_unchanged)
1653 return 0; /* we do not have to say --allow-empty */
1655 if (opts->keep_redundant_commits)
1656 return 1;
1658 originally_empty = is_original_commit_empty(commit);
1659 if (originally_empty < 0)
1660 return originally_empty;
1661 if (originally_empty)
1662 return 1;
1663 else if (opts->drop_redundant_commits)
1664 return 2;
1665 else
1666 return 0;
1669 static struct {
1670 char c;
1671 const char *str;
1672 } todo_command_info[] = {
1673 { 'p', "pick" },
1674 { 0, "revert" },
1675 { 'e', "edit" },
1676 { 'r', "reword" },
1677 { 'f', "fixup" },
1678 { 's', "squash" },
1679 { 'x', "exec" },
1680 { 'b', "break" },
1681 { 'l', "label" },
1682 { 't', "reset" },
1683 { 'm', "merge" },
1684 { 0, "noop" },
1685 { 'd', "drop" },
1686 { 0, NULL }
1689 static const char *command_to_string(const enum todo_command command)
1691 if (command < TODO_COMMENT)
1692 return todo_command_info[command].str;
1693 die(_("unknown command: %d"), command);
1696 static char command_to_char(const enum todo_command command)
1698 if (command < TODO_COMMENT)
1699 return todo_command_info[command].c;
1700 return comment_line_char;
1703 static int is_noop(const enum todo_command command)
1705 return TODO_NOOP <= command;
1708 static int is_fixup(enum todo_command command)
1710 return command == TODO_FIXUP || command == TODO_SQUASH;
1713 /* Does this command create a (non-merge) commit? */
1714 static int is_pick_or_similar(enum todo_command command)
1716 switch (command) {
1717 case TODO_PICK:
1718 case TODO_REVERT:
1719 case TODO_EDIT:
1720 case TODO_REWORD:
1721 case TODO_FIXUP:
1722 case TODO_SQUASH:
1723 return 1;
1724 default:
1725 return 0;
1729 enum todo_item_flags {
1730 TODO_EDIT_MERGE_MSG = (1 << 0),
1731 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1732 TODO_EDIT_FIXUP_MSG = (1 << 2),
1735 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1736 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1737 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1738 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1739 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1741 static int is_fixup_flag(enum todo_command command, unsigned flag)
1743 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1744 (flag & TODO_EDIT_FIXUP_MSG));
1748 * Wrapper around strbuf_add_commented_lines() which avoids double
1749 * commenting commit subjects.
1751 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1753 const char *s = str;
1754 while (len > 0 && s[0] == comment_line_char) {
1755 size_t count;
1756 const char *n = memchr(s, '\n', len);
1757 if (!n)
1758 count = len;
1759 else
1760 count = n - s + 1;
1761 strbuf_add(buf, s, count);
1762 s += count;
1763 len -= count;
1765 strbuf_add_commented_lines(buf, s, len);
1768 /* Does the current fixup chain contain a squash command? */
1769 static int seen_squash(struct replay_opts *opts)
1771 return starts_with(opts->current_fixups.buf, "squash") ||
1772 strstr(opts->current_fixups.buf, "\nsquash");
1775 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1777 strbuf_setlen(buf1, 2);
1778 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1779 strbuf_addch(buf1, '\n');
1780 strbuf_setlen(buf2, 2);
1781 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1782 strbuf_addch(buf2, '\n');
1786 * Comment out any un-commented commit messages, updating the message comments
1787 * to say they will be skipped but do not comment out the empty lines that
1788 * surround commit messages and their comments.
1790 static void update_squash_message_for_fixup(struct strbuf *msg)
1792 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1793 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1794 const char *s, *start;
1795 char *orig_msg;
1796 size_t orig_msg_len;
1797 int i = 1;
1799 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1800 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1801 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1802 while (s) {
1803 const char *next;
1804 size_t off;
1805 if (skip_prefix(s, buf1.buf, &next)) {
1807 * Copy the last message, preserving the blank line
1808 * preceding the current line
1810 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1811 copy_lines(msg, start, s - start - off);
1812 if (off)
1813 strbuf_addch(msg, '\n');
1815 * The next message needs to be commented out but the
1816 * message header is already commented out so just copy
1817 * it and the blank line that follows it.
1819 strbuf_addbuf(msg, &buf2);
1820 if (*next == '\n')
1821 strbuf_addch(msg, *next++);
1822 start = s = next;
1823 copy_lines = add_commented_lines;
1824 update_comment_bufs(&buf1, &buf2, ++i);
1825 } else if (skip_prefix(s, buf2.buf, &next)) {
1826 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1827 copy_lines(msg, start, s - start - off);
1828 start = s - off;
1829 s = next;
1830 copy_lines = strbuf_add;
1831 update_comment_bufs(&buf1, &buf2, ++i);
1832 } else {
1833 s = strchr(s, '\n');
1834 if (s)
1835 s++;
1838 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1839 free(orig_msg);
1840 strbuf_release(&buf1);
1841 strbuf_release(&buf2);
1844 static int append_squash_message(struct strbuf *buf, const char *body,
1845 enum todo_command command, struct replay_opts *opts,
1846 unsigned flag)
1848 const char *fixup_msg;
1849 size_t commented_len = 0, fixup_off;
1851 * amend is non-interactive and not normally used with fixup!
1852 * or squash! commits, so only comment out those subjects when
1853 * squashing commit messages.
1855 if (starts_with(body, "amend!") ||
1856 ((command == TODO_SQUASH || seen_squash(opts)) &&
1857 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1858 commented_len = commit_subject_length(body);
1860 strbuf_addf(buf, "\n%c ", comment_line_char);
1861 strbuf_addf(buf, _(nth_commit_msg_fmt),
1862 ++opts->current_fixup_count + 1);
1863 strbuf_addstr(buf, "\n\n");
1864 strbuf_add_commented_lines(buf, body, commented_len);
1865 /* buf->buf may be reallocated so store an offset into the buffer */
1866 fixup_off = buf->len;
1867 strbuf_addstr(buf, body + commented_len);
1869 /* fixup -C after squash behaves like squash */
1870 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1872 * We're replacing the commit message so we need to
1873 * append the Signed-off-by: trailer if the user
1874 * requested '--signoff'.
1876 if (opts->signoff)
1877 append_signoff(buf, 0, 0);
1879 if ((command == TODO_FIXUP) &&
1880 (flag & TODO_REPLACE_FIXUP_MSG) &&
1881 (file_exists(rebase_path_fixup_msg()) ||
1882 !file_exists(rebase_path_squash_msg()))) {
1883 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1884 if (write_message(fixup_msg, strlen(fixup_msg),
1885 rebase_path_fixup_msg(), 0) < 0)
1886 return error(_("cannot write '%s'"),
1887 rebase_path_fixup_msg());
1888 } else {
1889 unlink(rebase_path_fixup_msg());
1891 } else {
1892 unlink(rebase_path_fixup_msg());
1895 return 0;
1898 static int update_squash_messages(struct repository *r,
1899 enum todo_command command,
1900 struct commit *commit,
1901 struct replay_opts *opts,
1902 unsigned flag)
1904 struct strbuf buf = STRBUF_INIT;
1905 int res = 0;
1906 const char *message, *body;
1907 const char *encoding = get_commit_output_encoding();
1909 if (opts->current_fixup_count > 0) {
1910 struct strbuf header = STRBUF_INIT;
1911 char *eol;
1913 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1914 return error(_("could not read '%s'"),
1915 rebase_path_squash_msg());
1917 eol = buf.buf[0] != comment_line_char ?
1918 buf.buf : strchrnul(buf.buf, '\n');
1920 strbuf_addf(&header, "%c ", comment_line_char);
1921 strbuf_addf(&header, _(combined_commit_msg_fmt),
1922 opts->current_fixup_count + 2);
1923 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1924 strbuf_release(&header);
1925 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1926 update_squash_message_for_fixup(&buf);
1927 } else {
1928 struct object_id head;
1929 struct commit *head_commit;
1930 const char *head_message, *body;
1932 if (get_oid("HEAD", &head))
1933 return error(_("need a HEAD to fixup"));
1934 if (!(head_commit = lookup_commit_reference(r, &head)))
1935 return error(_("could not read HEAD"));
1936 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1937 return error(_("could not read HEAD's commit message"));
1939 find_commit_subject(head_message, &body);
1940 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1941 rebase_path_fixup_msg(), 0) < 0) {
1942 unuse_commit_buffer(head_commit, head_message);
1943 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1945 strbuf_addf(&buf, "%c ", comment_line_char);
1946 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1947 strbuf_addf(&buf, "\n%c ", comment_line_char);
1948 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1949 _(skip_first_commit_msg_str) :
1950 _(first_commit_msg_str));
1951 strbuf_addstr(&buf, "\n\n");
1952 if (is_fixup_flag(command, flag))
1953 strbuf_add_commented_lines(&buf, body, strlen(body));
1954 else
1955 strbuf_addstr(&buf, body);
1957 unuse_commit_buffer(head_commit, head_message);
1960 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1961 return error(_("could not read commit message of %s"),
1962 oid_to_hex(&commit->object.oid));
1963 find_commit_subject(message, &body);
1965 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1966 res = append_squash_message(&buf, body, command, opts, flag);
1967 } else if (command == TODO_FIXUP) {
1968 strbuf_addf(&buf, "\n%c ", comment_line_char);
1969 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1970 ++opts->current_fixup_count + 1);
1971 strbuf_addstr(&buf, "\n\n");
1972 strbuf_add_commented_lines(&buf, body, strlen(body));
1973 } else
1974 return error(_("unknown command: %d"), command);
1975 unuse_commit_buffer(commit, message);
1977 if (!res)
1978 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1980 strbuf_release(&buf);
1982 if (!res) {
1983 strbuf_addf(&opts->current_fixups, "%s%s %s",
1984 opts->current_fixups.len ? "\n" : "",
1985 command_to_string(command),
1986 oid_to_hex(&commit->object.oid));
1987 res = write_message(opts->current_fixups.buf,
1988 opts->current_fixups.len,
1989 rebase_path_current_fixups(), 0);
1992 return res;
1995 static void flush_rewritten_pending(void)
1997 struct strbuf buf = STRBUF_INIT;
1998 struct object_id newoid;
1999 FILE *out;
2001 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2002 !get_oid("HEAD", &newoid) &&
2003 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2004 char *bol = buf.buf, *eol;
2006 while (*bol) {
2007 eol = strchrnul(bol, '\n');
2008 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2009 bol, oid_to_hex(&newoid));
2010 if (!*eol)
2011 break;
2012 bol = eol + 1;
2014 fclose(out);
2015 unlink(rebase_path_rewritten_pending());
2017 strbuf_release(&buf);
2020 static void record_in_rewritten(struct object_id *oid,
2021 enum todo_command next_command)
2023 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2025 if (!out)
2026 return;
2028 fprintf(out, "%s\n", oid_to_hex(oid));
2029 fclose(out);
2031 if (!is_fixup(next_command))
2032 flush_rewritten_pending();
2035 static int do_pick_commit(struct repository *r,
2036 struct todo_item *item,
2037 struct replay_opts *opts,
2038 int final_fixup, int *check_todo)
2040 unsigned int flags = opts->edit ? EDIT_MSG : 0;
2041 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
2042 struct object_id head;
2043 struct commit *base, *next, *parent;
2044 const char *base_label, *next_label;
2045 char *author = NULL;
2046 struct commit_message msg = { NULL, NULL, NULL, NULL };
2047 struct strbuf msgbuf = STRBUF_INIT;
2048 int res, unborn = 0, reword = 0, allow, drop_commit;
2049 enum todo_command command = item->command;
2050 struct commit *commit = item->commit;
2052 if (opts->no_commit) {
2054 * We do not intend to commit immediately. We just want to
2055 * merge the differences in, so let's compute the tree
2056 * that represents the "current" state for merge-recursive
2057 * to work on.
2059 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2060 return error(_("your index file is unmerged."));
2061 } else {
2062 unborn = get_oid("HEAD", &head);
2063 /* Do we want to generate a root commit? */
2064 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2065 oideq(&head, &opts->squash_onto)) {
2066 if (is_fixup(command))
2067 return error(_("cannot fixup root commit"));
2068 flags |= CREATE_ROOT_COMMIT;
2069 unborn = 1;
2070 } else if (unborn)
2071 oidcpy(&head, the_hash_algo->empty_tree);
2072 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2073 NULL, 0))
2074 return error_dirty_index(r, opts);
2076 discard_index(r->index);
2078 if (!commit->parents)
2079 parent = NULL;
2080 else if (commit->parents->next) {
2081 /* Reverting or cherry-picking a merge commit */
2082 int cnt;
2083 struct commit_list *p;
2085 if (!opts->mainline)
2086 return error(_("commit %s is a merge but no -m option was given."),
2087 oid_to_hex(&commit->object.oid));
2089 for (cnt = 1, p = commit->parents;
2090 cnt != opts->mainline && p;
2091 cnt++)
2092 p = p->next;
2093 if (cnt != opts->mainline || !p)
2094 return error(_("commit %s does not have parent %d"),
2095 oid_to_hex(&commit->object.oid), opts->mainline);
2096 parent = p->item;
2097 } else if (1 < opts->mainline)
2099 * Non-first parent explicitly specified as mainline for
2100 * non-merge commit
2102 return error(_("commit %s does not have parent %d"),
2103 oid_to_hex(&commit->object.oid), opts->mainline);
2104 else
2105 parent = commit->parents->item;
2107 if (get_message(commit, &msg) != 0)
2108 return error(_("cannot get commit message for %s"),
2109 oid_to_hex(&commit->object.oid));
2111 if (opts->allow_ff && !is_fixup(command) &&
2112 ((parent && oideq(&parent->object.oid, &head)) ||
2113 (!parent && unborn))) {
2114 if (is_rebase_i(opts))
2115 write_author_script(msg.message);
2116 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2117 opts);
2118 if (res || command != TODO_REWORD)
2119 goto leave;
2120 reword = 1;
2121 msg_file = NULL;
2122 goto fast_forward_edit;
2124 if (parent && parse_commit(parent) < 0)
2125 /* TRANSLATORS: The first %s will be a "todo" command like
2126 "revert" or "pick", the second %s a SHA1. */
2127 return error(_("%s: cannot parse parent commit %s"),
2128 command_to_string(command),
2129 oid_to_hex(&parent->object.oid));
2132 * "commit" is an existing commit. We would want to apply
2133 * the difference it introduces since its first parent "prev"
2134 * on top of the current HEAD if we are cherry-pick. Or the
2135 * reverse of it if we are revert.
2138 if (command == TODO_REVERT) {
2139 base = commit;
2140 base_label = msg.label;
2141 next = parent;
2142 next_label = msg.parent_label;
2143 strbuf_addstr(&msgbuf, "Revert \"");
2144 strbuf_addstr(&msgbuf, msg.subject);
2145 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2146 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2148 if (commit->parents && commit->parents->next) {
2149 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2150 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2152 strbuf_addstr(&msgbuf, ".\n");
2153 } else {
2154 const char *p;
2156 base = parent;
2157 base_label = msg.parent_label;
2158 next = commit;
2159 next_label = msg.label;
2161 /* Append the commit log message to msgbuf. */
2162 if (find_commit_subject(msg.message, &p))
2163 strbuf_addstr(&msgbuf, p);
2165 if (opts->record_origin) {
2166 strbuf_complete_line(&msgbuf);
2167 if (!has_conforming_footer(&msgbuf, NULL, 0))
2168 strbuf_addch(&msgbuf, '\n');
2169 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2170 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2171 strbuf_addstr(&msgbuf, ")\n");
2173 if (!is_fixup(command))
2174 author = get_author(msg.message);
2177 if (command == TODO_REWORD)
2178 reword = 1;
2179 else if (is_fixup(command)) {
2180 if (update_squash_messages(r, command, commit,
2181 opts, item->flags))
2182 return -1;
2183 flags |= AMEND_MSG;
2184 if (!final_fixup)
2185 msg_file = rebase_path_squash_msg();
2186 else if (file_exists(rebase_path_fixup_msg())) {
2187 flags |= VERBATIM_MSG;
2188 msg_file = rebase_path_fixup_msg();
2189 } else {
2190 const char *dest = git_path_squash_msg(r);
2191 unlink(dest);
2192 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2193 return error(_("could not rename '%s' to '%s'"),
2194 rebase_path_squash_msg(), dest);
2195 unlink(git_path_merge_msg(r));
2196 msg_file = dest;
2197 flags |= EDIT_MSG;
2201 if (opts->signoff && !is_fixup(command))
2202 append_signoff(&msgbuf, 0, 0);
2204 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2205 res = -1;
2206 else if (!opts->strategy ||
2207 !strcmp(opts->strategy, "recursive") ||
2208 !strcmp(opts->strategy, "ort") ||
2209 command == TODO_REVERT) {
2210 res = do_recursive_merge(r, base, next, base_label, next_label,
2211 &head, &msgbuf, opts);
2212 if (res < 0)
2213 goto leave;
2215 res |= write_message(msgbuf.buf, msgbuf.len,
2216 git_path_merge_msg(r), 0);
2217 } else {
2218 struct commit_list *common = NULL;
2219 struct commit_list *remotes = NULL;
2221 res = write_message(msgbuf.buf, msgbuf.len,
2222 git_path_merge_msg(r), 0);
2224 commit_list_insert(base, &common);
2225 commit_list_insert(next, &remotes);
2226 res |= try_merge_command(r, opts->strategy,
2227 opts->xopts_nr, (const char **)opts->xopts,
2228 common, oid_to_hex(&head), remotes);
2229 free_commit_list(common);
2230 free_commit_list(remotes);
2232 strbuf_release(&msgbuf);
2235 * If the merge was clean or if it failed due to conflict, we write
2236 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2237 * However, if the merge did not even start, then we don't want to
2238 * write it at all.
2240 if ((command == TODO_PICK || command == TODO_REWORD ||
2241 command == TODO_EDIT) && !opts->no_commit &&
2242 (res == 0 || res == 1) &&
2243 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2244 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2245 res = -1;
2246 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2247 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2248 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2249 res = -1;
2251 if (res) {
2252 error(command == TODO_REVERT
2253 ? _("could not revert %s... %s")
2254 : _("could not apply %s... %s"),
2255 short_commit_name(commit), msg.subject);
2256 print_advice(r, res == 1, opts);
2257 repo_rerere(r, opts->allow_rerere_auto);
2258 goto leave;
2261 drop_commit = 0;
2262 allow = allow_empty(r, opts, commit);
2263 if (allow < 0) {
2264 res = allow;
2265 goto leave;
2266 } else if (allow == 1) {
2267 flags |= ALLOW_EMPTY;
2268 } else if (allow == 2) {
2269 drop_commit = 1;
2270 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2271 NULL, 0);
2272 unlink(git_path_merge_msg(r));
2273 fprintf(stderr,
2274 _("dropping %s %s -- patch contents already upstream\n"),
2275 oid_to_hex(&commit->object.oid), msg.subject);
2276 } /* else allow == 0 and there's nothing special to do */
2277 if (!opts->no_commit && !drop_commit) {
2278 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2279 res = do_commit(r, msg_file, author, opts, flags,
2280 commit? &commit->object.oid : NULL);
2281 else
2282 res = error(_("unable to parse commit author"));
2283 *check_todo = !!(flags & EDIT_MSG);
2284 if (!res && reword) {
2285 fast_forward_edit:
2286 res = run_git_commit(NULL, opts, EDIT_MSG |
2287 VERIFY_MSG | AMEND_MSG |
2288 (flags & ALLOW_EMPTY));
2289 *check_todo = 1;
2294 if (!res && final_fixup) {
2295 unlink(rebase_path_fixup_msg());
2296 unlink(rebase_path_squash_msg());
2297 unlink(rebase_path_current_fixups());
2298 strbuf_reset(&opts->current_fixups);
2299 opts->current_fixup_count = 0;
2302 leave:
2303 free_message(commit, &msg);
2304 free(author);
2305 update_abort_safety_file();
2307 return res;
2310 static int prepare_revs(struct replay_opts *opts)
2313 * picking (but not reverting) ranges (but not individual revisions)
2314 * should be done in reverse
2316 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2317 opts->revs->reverse ^= 1;
2319 if (prepare_revision_walk(opts->revs))
2320 return error(_("revision walk setup failed"));
2322 return 0;
2325 static int read_and_refresh_cache(struct repository *r,
2326 struct replay_opts *opts)
2328 struct lock_file index_lock = LOCK_INIT;
2329 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2330 if (repo_read_index(r) < 0) {
2331 rollback_lock_file(&index_lock);
2332 return error(_("git %s: failed to read the index"),
2333 _(action_name(opts)));
2335 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2336 if (index_fd >= 0) {
2337 if (write_locked_index(r->index, &index_lock,
2338 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2339 return error(_("git %s: failed to refresh the index"),
2340 _(action_name(opts)));
2343 return 0;
2346 void todo_list_release(struct todo_list *todo_list)
2348 strbuf_release(&todo_list->buf);
2349 FREE_AND_NULL(todo_list->items);
2350 todo_list->nr = todo_list->alloc = 0;
2353 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2355 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2356 todo_list->total_nr++;
2357 return todo_list->items + todo_list->nr++;
2360 const char *todo_item_get_arg(struct todo_list *todo_list,
2361 struct todo_item *item)
2363 return todo_list->buf.buf + item->arg_offset;
2366 static int is_command(enum todo_command command, const char **bol)
2368 const char *str = todo_command_info[command].str;
2369 const char nick = todo_command_info[command].c;
2370 const char *p = *bol + 1;
2372 return skip_prefix(*bol, str, bol) ||
2373 ((nick && **bol == nick) &&
2374 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2375 (*bol = p));
2378 static int parse_insn_line(struct repository *r, struct todo_item *item,
2379 const char *buf, const char *bol, char *eol)
2381 struct object_id commit_oid;
2382 char *end_of_object_name;
2383 int i, saved, status, padding;
2385 item->flags = 0;
2387 /* left-trim */
2388 bol += strspn(bol, " \t");
2390 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2391 item->command = TODO_COMMENT;
2392 item->commit = NULL;
2393 item->arg_offset = bol - buf;
2394 item->arg_len = eol - bol;
2395 return 0;
2398 for (i = 0; i < TODO_COMMENT; i++)
2399 if (is_command(i, &bol)) {
2400 item->command = i;
2401 break;
2403 if (i >= TODO_COMMENT)
2404 return -1;
2406 /* Eat up extra spaces/ tabs before object name */
2407 padding = strspn(bol, " \t");
2408 bol += padding;
2410 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2411 if (bol != eol)
2412 return error(_("%s does not accept arguments: '%s'"),
2413 command_to_string(item->command), bol);
2414 item->commit = NULL;
2415 item->arg_offset = bol - buf;
2416 item->arg_len = eol - bol;
2417 return 0;
2420 if (!padding)
2421 return error(_("missing arguments for %s"),
2422 command_to_string(item->command));
2424 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2425 item->command == TODO_RESET) {
2426 item->commit = NULL;
2427 item->arg_offset = bol - buf;
2428 item->arg_len = (int)(eol - bol);
2429 return 0;
2432 if (item->command == TODO_FIXUP) {
2433 if (skip_prefix(bol, "-C", &bol) &&
2434 (*bol == ' ' || *bol == '\t')) {
2435 bol += strspn(bol, " \t");
2436 item->flags |= TODO_REPLACE_FIXUP_MSG;
2437 } else if (skip_prefix(bol, "-c", &bol) &&
2438 (*bol == ' ' || *bol == '\t')) {
2439 bol += strspn(bol, " \t");
2440 item->flags |= TODO_EDIT_FIXUP_MSG;
2444 if (item->command == TODO_MERGE) {
2445 if (skip_prefix(bol, "-C", &bol))
2446 bol += strspn(bol, " \t");
2447 else if (skip_prefix(bol, "-c", &bol)) {
2448 bol += strspn(bol, " \t");
2449 item->flags |= TODO_EDIT_MERGE_MSG;
2450 } else {
2451 item->flags |= TODO_EDIT_MERGE_MSG;
2452 item->commit = NULL;
2453 item->arg_offset = bol - buf;
2454 item->arg_len = (int)(eol - bol);
2455 return 0;
2459 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2460 saved = *end_of_object_name;
2461 *end_of_object_name = '\0';
2462 status = get_oid(bol, &commit_oid);
2463 if (status < 0)
2464 error(_("could not parse '%s'"), bol); /* return later */
2465 *end_of_object_name = saved;
2467 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2468 item->arg_offset = bol - buf;
2469 item->arg_len = (int)(eol - bol);
2471 if (status < 0)
2472 return status;
2474 item->commit = lookup_commit_reference(r, &commit_oid);
2475 return item->commit ? 0 : -1;
2478 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2480 const char *todo_file, *bol;
2481 struct strbuf buf = STRBUF_INIT;
2482 int ret = 0;
2484 todo_file = git_path_todo_file();
2485 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2486 if (errno == ENOENT || errno == ENOTDIR)
2487 return -1;
2488 else
2489 return error_errno("unable to open '%s'", todo_file);
2491 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2492 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2493 *action = REPLAY_PICK;
2494 else if (is_command(TODO_REVERT, &bol) &&
2495 (*bol == ' ' || *bol == '\t'))
2496 *action = REPLAY_REVERT;
2497 else
2498 ret = -1;
2500 strbuf_release(&buf);
2502 return ret;
2505 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2506 struct todo_list *todo_list)
2508 struct todo_item *item;
2509 char *p = buf, *next_p;
2510 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2512 todo_list->current = todo_list->nr = 0;
2514 for (i = 1; *p; i++, p = next_p) {
2515 char *eol = strchrnul(p, '\n');
2517 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2519 if (p != eol && eol[-1] == '\r')
2520 eol--; /* strip Carriage Return */
2522 item = append_new_todo(todo_list);
2523 item->offset_in_buf = p - todo_list->buf.buf;
2524 if (parse_insn_line(r, item, buf, p, eol)) {
2525 res = error(_("invalid line %d: %.*s"),
2526 i, (int)(eol - p), p);
2527 item->command = TODO_COMMENT + 1;
2528 item->arg_offset = p - buf;
2529 item->arg_len = (int)(eol - p);
2530 item->commit = NULL;
2533 if (fixup_okay)
2534 ; /* do nothing */
2535 else if (is_fixup(item->command))
2536 return error(_("cannot '%s' without a previous commit"),
2537 command_to_string(item->command));
2538 else if (!is_noop(item->command))
2539 fixup_okay = 1;
2542 return res;
2545 static int count_commands(struct todo_list *todo_list)
2547 int count = 0, i;
2549 for (i = 0; i < todo_list->nr; i++)
2550 if (todo_list->items[i].command != TODO_COMMENT)
2551 count++;
2553 return count;
2556 static int get_item_line_offset(struct todo_list *todo_list, int index)
2558 return index < todo_list->nr ?
2559 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2562 static const char *get_item_line(struct todo_list *todo_list, int index)
2564 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2567 static int get_item_line_length(struct todo_list *todo_list, int index)
2569 return get_item_line_offset(todo_list, index + 1)
2570 - get_item_line_offset(todo_list, index);
2573 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2575 int fd;
2576 ssize_t len;
2578 fd = open(path, O_RDONLY);
2579 if (fd < 0)
2580 return error_errno(_("could not open '%s'"), path);
2581 len = strbuf_read(sb, fd, 0);
2582 close(fd);
2583 if (len < 0)
2584 return error(_("could not read '%s'."), path);
2585 return len;
2588 static int have_finished_the_last_pick(void)
2590 struct strbuf buf = STRBUF_INIT;
2591 const char *eol;
2592 const char *todo_path = git_path_todo_file();
2593 int ret = 0;
2595 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2596 if (errno == ENOENT) {
2597 return 0;
2598 } else {
2599 error_errno("unable to open '%s'", todo_path);
2600 return 0;
2603 /* If there is only one line then we are done */
2604 eol = strchr(buf.buf, '\n');
2605 if (!eol || !eol[1])
2606 ret = 1;
2608 strbuf_release(&buf);
2610 return ret;
2613 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2615 struct replay_opts opts = REPLAY_OPTS_INIT;
2616 int need_cleanup = 0;
2618 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2619 if (!refs_delete_ref(get_main_ref_store(r), "",
2620 "CHERRY_PICK_HEAD", NULL, 0) &&
2621 verbose)
2622 warning(_("cancelling a cherry picking in progress"));
2623 opts.action = REPLAY_PICK;
2624 need_cleanup = 1;
2627 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2628 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2629 NULL, 0) &&
2630 verbose)
2631 warning(_("cancelling a revert in progress"));
2632 opts.action = REPLAY_REVERT;
2633 need_cleanup = 1;
2636 if (!need_cleanup)
2637 return;
2639 if (!have_finished_the_last_pick())
2640 return;
2642 sequencer_remove_state(&opts);
2645 static void todo_list_write_total_nr(struct todo_list *todo_list)
2647 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2649 if (f) {
2650 fprintf(f, "%d\n", todo_list->total_nr);
2651 fclose(f);
2655 static int read_populate_todo(struct repository *r,
2656 struct todo_list *todo_list,
2657 struct replay_opts *opts)
2659 struct stat st;
2660 const char *todo_file = get_todo_path(opts);
2661 int res;
2663 strbuf_reset(&todo_list->buf);
2664 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2665 return -1;
2667 res = stat(todo_file, &st);
2668 if (res)
2669 return error(_("could not stat '%s'"), todo_file);
2670 fill_stat_data(&todo_list->stat, &st);
2672 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2673 if (res) {
2674 if (is_rebase_i(opts))
2675 return error(_("please fix this using "
2676 "'git rebase --edit-todo'."));
2677 return error(_("unusable instruction sheet: '%s'"), todo_file);
2680 if (!todo_list->nr &&
2681 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2682 return error(_("no commits parsed."));
2684 if (!is_rebase_i(opts)) {
2685 enum todo_command valid =
2686 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2687 int i;
2689 for (i = 0; i < todo_list->nr; i++)
2690 if (valid == todo_list->items[i].command)
2691 continue;
2692 else if (valid == TODO_PICK)
2693 return error(_("cannot cherry-pick during a revert."));
2694 else
2695 return error(_("cannot revert during a cherry-pick."));
2698 if (is_rebase_i(opts)) {
2699 struct todo_list done = TODO_LIST_INIT;
2701 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2702 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2703 todo_list->done_nr = count_commands(&done);
2704 else
2705 todo_list->done_nr = 0;
2707 todo_list->total_nr = todo_list->done_nr
2708 + count_commands(todo_list);
2709 todo_list_release(&done);
2711 todo_list_write_total_nr(todo_list);
2714 return 0;
2717 static int git_config_string_dup(char **dest,
2718 const char *var, const char *value)
2720 if (!value)
2721 return config_error_nonbool(var);
2722 free(*dest);
2723 *dest = xstrdup(value);
2724 return 0;
2727 static int populate_opts_cb(const char *key, const char *value, void *data)
2729 struct replay_opts *opts = data;
2730 int error_flag = 1;
2732 if (!value)
2733 error_flag = 0;
2734 else if (!strcmp(key, "options.no-commit"))
2735 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2736 else if (!strcmp(key, "options.edit"))
2737 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2738 else if (!strcmp(key, "options.allow-empty"))
2739 opts->allow_empty =
2740 git_config_bool_or_int(key, value, &error_flag);
2741 else if (!strcmp(key, "options.allow-empty-message"))
2742 opts->allow_empty_message =
2743 git_config_bool_or_int(key, value, &error_flag);
2744 else if (!strcmp(key, "options.keep-redundant-commits"))
2745 opts->keep_redundant_commits =
2746 git_config_bool_or_int(key, value, &error_flag);
2747 else if (!strcmp(key, "options.signoff"))
2748 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2749 else if (!strcmp(key, "options.record-origin"))
2750 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2751 else if (!strcmp(key, "options.allow-ff"))
2752 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2753 else if (!strcmp(key, "options.mainline"))
2754 opts->mainline = git_config_int(key, value);
2755 else if (!strcmp(key, "options.strategy"))
2756 git_config_string_dup(&opts->strategy, key, value);
2757 else if (!strcmp(key, "options.gpg-sign"))
2758 git_config_string_dup(&opts->gpg_sign, key, value);
2759 else if (!strcmp(key, "options.strategy-option")) {
2760 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2761 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2762 } else if (!strcmp(key, "options.allow-rerere-auto"))
2763 opts->allow_rerere_auto =
2764 git_config_bool_or_int(key, value, &error_flag) ?
2765 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2766 else if (!strcmp(key, "options.default-msg-cleanup")) {
2767 opts->explicit_cleanup = 1;
2768 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2769 } else
2770 return error(_("invalid key: %s"), key);
2772 if (!error_flag)
2773 return error(_("invalid value for %s: %s"), key, value);
2775 return 0;
2778 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2780 int i;
2781 char *strategy_opts_string = raw_opts;
2783 if (*strategy_opts_string == ' ')
2784 strategy_opts_string++;
2786 opts->xopts_nr = split_cmdline(strategy_opts_string,
2787 (const char ***)&opts->xopts);
2788 for (i = 0; i < opts->xopts_nr; i++) {
2789 const char *arg = opts->xopts[i];
2791 skip_prefix(arg, "--", &arg);
2792 opts->xopts[i] = xstrdup(arg);
2796 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2798 strbuf_reset(buf);
2799 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2800 return;
2801 opts->strategy = strbuf_detach(buf, NULL);
2802 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2803 return;
2805 parse_strategy_opts(opts, buf->buf);
2808 static int read_populate_opts(struct replay_opts *opts)
2810 if (is_rebase_i(opts)) {
2811 struct strbuf buf = STRBUF_INIT;
2812 int ret = 0;
2814 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2815 READ_ONELINER_SKIP_IF_EMPTY)) {
2816 if (!starts_with(buf.buf, "-S"))
2817 strbuf_reset(&buf);
2818 else {
2819 free(opts->gpg_sign);
2820 opts->gpg_sign = xstrdup(buf.buf + 2);
2822 strbuf_reset(&buf);
2825 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2826 READ_ONELINER_SKIP_IF_EMPTY)) {
2827 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2828 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2829 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2830 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2831 strbuf_reset(&buf);
2834 if (file_exists(rebase_path_verbose()))
2835 opts->verbose = 1;
2837 if (file_exists(rebase_path_quiet()))
2838 opts->quiet = 1;
2840 if (file_exists(rebase_path_signoff())) {
2841 opts->allow_ff = 0;
2842 opts->signoff = 1;
2845 if (file_exists(rebase_path_cdate_is_adate())) {
2846 opts->allow_ff = 0;
2847 opts->committer_date_is_author_date = 1;
2850 if (file_exists(rebase_path_ignore_date())) {
2851 opts->allow_ff = 0;
2852 opts->ignore_date = 1;
2855 if (file_exists(rebase_path_reschedule_failed_exec()))
2856 opts->reschedule_failed_exec = 1;
2858 if (file_exists(rebase_path_drop_redundant_commits()))
2859 opts->drop_redundant_commits = 1;
2861 if (file_exists(rebase_path_keep_redundant_commits()))
2862 opts->keep_redundant_commits = 1;
2864 read_strategy_opts(opts, &buf);
2865 strbuf_reset(&buf);
2867 if (read_oneliner(&opts->current_fixups,
2868 rebase_path_current_fixups(),
2869 READ_ONELINER_SKIP_IF_EMPTY)) {
2870 const char *p = opts->current_fixups.buf;
2871 opts->current_fixup_count = 1;
2872 while ((p = strchr(p, '\n'))) {
2873 opts->current_fixup_count++;
2874 p++;
2878 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2879 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2880 ret = error(_("unusable squash-onto"));
2881 goto done_rebase_i;
2883 opts->have_squash_onto = 1;
2886 done_rebase_i:
2887 strbuf_release(&buf);
2888 return ret;
2891 if (!file_exists(git_path_opts_file()))
2892 return 0;
2894 * The function git_parse_source(), called from git_config_from_file(),
2895 * may die() in case of a syntactically incorrect file. We do not care
2896 * about this case, though, because we wrote that file ourselves, so we
2897 * are pretty certain that it is syntactically correct.
2899 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2900 return error(_("malformed options sheet: '%s'"),
2901 git_path_opts_file());
2902 return 0;
2905 static void write_strategy_opts(struct replay_opts *opts)
2907 int i;
2908 struct strbuf buf = STRBUF_INIT;
2910 for (i = 0; i < opts->xopts_nr; ++i)
2911 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2913 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2914 strbuf_release(&buf);
2917 int write_basic_state(struct replay_opts *opts, const char *head_name,
2918 struct commit *onto, const struct object_id *orig_head)
2920 if (head_name)
2921 write_file(rebase_path_head_name(), "%s\n", head_name);
2922 if (onto)
2923 write_file(rebase_path_onto(), "%s\n",
2924 oid_to_hex(&onto->object.oid));
2925 if (orig_head)
2926 write_file(rebase_path_orig_head(), "%s\n",
2927 oid_to_hex(orig_head));
2929 if (opts->quiet)
2930 write_file(rebase_path_quiet(), "%s", "");
2931 if (opts->verbose)
2932 write_file(rebase_path_verbose(), "%s", "");
2933 if (opts->strategy)
2934 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2935 if (opts->xopts_nr > 0)
2936 write_strategy_opts(opts);
2938 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2939 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2940 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2941 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2943 if (opts->gpg_sign)
2944 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2945 if (opts->signoff)
2946 write_file(rebase_path_signoff(), "--signoff\n");
2947 if (opts->drop_redundant_commits)
2948 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2949 if (opts->keep_redundant_commits)
2950 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2951 if (opts->committer_date_is_author_date)
2952 write_file(rebase_path_cdate_is_adate(), "%s", "");
2953 if (opts->ignore_date)
2954 write_file(rebase_path_ignore_date(), "%s", "");
2955 if (opts->reschedule_failed_exec)
2956 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2958 return 0;
2961 static int walk_revs_populate_todo(struct todo_list *todo_list,
2962 struct replay_opts *opts)
2964 enum todo_command command = opts->action == REPLAY_PICK ?
2965 TODO_PICK : TODO_REVERT;
2966 const char *command_string = todo_command_info[command].str;
2967 const char *encoding;
2968 struct commit *commit;
2970 if (prepare_revs(opts))
2971 return -1;
2973 encoding = get_log_output_encoding();
2975 while ((commit = get_revision(opts->revs))) {
2976 struct todo_item *item = append_new_todo(todo_list);
2977 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2978 const char *subject;
2979 int subject_len;
2981 item->command = command;
2982 item->commit = commit;
2983 item->arg_offset = 0;
2984 item->arg_len = 0;
2985 item->offset_in_buf = todo_list->buf.len;
2986 subject_len = find_commit_subject(commit_buffer, &subject);
2987 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2988 short_commit_name(commit), subject_len, subject);
2989 unuse_commit_buffer(commit, commit_buffer);
2992 if (!todo_list->nr)
2993 return error(_("empty commit set passed"));
2995 return 0;
2998 static int create_seq_dir(struct repository *r)
3000 enum replay_action action;
3001 const char *in_progress_error = NULL;
3002 const char *in_progress_advice = NULL;
3003 unsigned int advise_skip =
3004 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3005 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3007 if (!sequencer_get_last_command(r, &action)) {
3008 switch (action) {
3009 case REPLAY_REVERT:
3010 in_progress_error = _("revert is already in progress");
3011 in_progress_advice =
3012 _("try \"git revert (--continue | %s--abort | --quit)\"");
3013 break;
3014 case REPLAY_PICK:
3015 in_progress_error = _("cherry-pick is already in progress");
3016 in_progress_advice =
3017 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3018 break;
3019 default:
3020 BUG("unexpected action in create_seq_dir");
3023 if (in_progress_error) {
3024 error("%s", in_progress_error);
3025 if (advice_sequencer_in_use)
3026 advise(in_progress_advice,
3027 advise_skip ? "--skip | " : "");
3028 return -1;
3030 if (mkdir(git_path_seq_dir(), 0777) < 0)
3031 return error_errno(_("could not create sequencer directory '%s'"),
3032 git_path_seq_dir());
3034 return 0;
3037 static int save_head(const char *head)
3039 struct lock_file head_lock = LOCK_INIT;
3040 struct strbuf buf = STRBUF_INIT;
3041 int fd;
3042 ssize_t written;
3044 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3045 if (fd < 0)
3046 return error_errno(_("could not lock HEAD"));
3047 strbuf_addf(&buf, "%s\n", head);
3048 written = write_in_full(fd, buf.buf, buf.len);
3049 strbuf_release(&buf);
3050 if (written < 0) {
3051 error_errno(_("could not write to '%s'"), git_path_head_file());
3052 rollback_lock_file(&head_lock);
3053 return -1;
3055 if (commit_lock_file(&head_lock) < 0)
3056 return error(_("failed to finalize '%s'"), git_path_head_file());
3057 return 0;
3060 static int rollback_is_safe(void)
3062 struct strbuf sb = STRBUF_INIT;
3063 struct object_id expected_head, actual_head;
3065 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3066 strbuf_trim(&sb);
3067 if (get_oid_hex(sb.buf, &expected_head)) {
3068 strbuf_release(&sb);
3069 die(_("could not parse %s"), git_path_abort_safety_file());
3071 strbuf_release(&sb);
3073 else if (errno == ENOENT)
3074 oidclr(&expected_head);
3075 else
3076 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3078 if (get_oid("HEAD", &actual_head))
3079 oidclr(&actual_head);
3081 return oideq(&actual_head, &expected_head);
3084 static int reset_merge(const struct object_id *oid)
3086 int ret;
3087 struct strvec argv = STRVEC_INIT;
3089 strvec_pushl(&argv, "reset", "--merge", NULL);
3091 if (!is_null_oid(oid))
3092 strvec_push(&argv, oid_to_hex(oid));
3094 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3095 strvec_clear(&argv);
3097 return ret;
3100 static int rollback_single_pick(struct repository *r)
3102 struct object_id head_oid;
3104 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3105 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3106 return error(_("no cherry-pick or revert in progress"));
3107 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3108 return error(_("cannot resolve HEAD"));
3109 if (is_null_oid(&head_oid))
3110 return error(_("cannot abort from a branch yet to be born"));
3111 return reset_merge(&head_oid);
3114 static int skip_single_pick(void)
3116 struct object_id head;
3118 if (read_ref_full("HEAD", 0, &head, NULL))
3119 return error(_("cannot resolve HEAD"));
3120 return reset_merge(&head);
3123 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3125 FILE *f;
3126 struct object_id oid;
3127 struct strbuf buf = STRBUF_INIT;
3128 const char *p;
3130 f = fopen(git_path_head_file(), "r");
3131 if (!f && errno == ENOENT) {
3133 * There is no multiple-cherry-pick in progress.
3134 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3135 * a single-cherry-pick in progress, abort that.
3137 return rollback_single_pick(r);
3139 if (!f)
3140 return error_errno(_("cannot open '%s'"), git_path_head_file());
3141 if (strbuf_getline_lf(&buf, f)) {
3142 error(_("cannot read '%s': %s"), git_path_head_file(),
3143 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3144 fclose(f);
3145 goto fail;
3147 fclose(f);
3148 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3149 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3150 git_path_head_file());
3151 goto fail;
3153 if (is_null_oid(&oid)) {
3154 error(_("cannot abort from a branch yet to be born"));
3155 goto fail;
3158 if (!rollback_is_safe()) {
3159 /* Do not error, just do not rollback */
3160 warning(_("You seem to have moved HEAD. "
3161 "Not rewinding, check your HEAD!"));
3162 } else
3163 if (reset_merge(&oid))
3164 goto fail;
3165 strbuf_release(&buf);
3166 return sequencer_remove_state(opts);
3167 fail:
3168 strbuf_release(&buf);
3169 return -1;
3172 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3174 enum replay_action action = -1;
3175 sequencer_get_last_command(r, &action);
3178 * Check whether the subcommand requested to skip the commit is actually
3179 * in progress and that it's safe to skip the commit.
3181 * opts->action tells us which subcommand requested to skip the commit.
3182 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3183 * action is in progress and we can skip the commit.
3185 * Otherwise we check that the last instruction was related to the
3186 * particular subcommand we're trying to execute and barf if that's not
3187 * the case.
3189 * Finally we check that the rollback is "safe", i.e., has the HEAD
3190 * moved? In this case, it doesn't make sense to "reset the merge" and
3191 * "skip the commit" as the user already handled this by committing. But
3192 * we'd not want to barf here, instead give advice on how to proceed. We
3193 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3194 * it gets removed when the user commits, so if it still exists we're
3195 * sure the user can't have committed before.
3197 switch (opts->action) {
3198 case REPLAY_REVERT:
3199 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3200 if (action != REPLAY_REVERT)
3201 return error(_("no revert in progress"));
3202 if (!rollback_is_safe())
3203 goto give_advice;
3205 break;
3206 case REPLAY_PICK:
3207 if (!refs_ref_exists(get_main_ref_store(r),
3208 "CHERRY_PICK_HEAD")) {
3209 if (action != REPLAY_PICK)
3210 return error(_("no cherry-pick in progress"));
3211 if (!rollback_is_safe())
3212 goto give_advice;
3214 break;
3215 default:
3216 BUG("unexpected action in sequencer_skip");
3219 if (skip_single_pick())
3220 return error(_("failed to skip the commit"));
3221 if (!is_directory(git_path_seq_dir()))
3222 return 0;
3224 return sequencer_continue(r, opts);
3226 give_advice:
3227 error(_("there is nothing to skip"));
3229 if (advice_resolve_conflict) {
3230 advise(_("have you committed already?\n"
3231 "try \"git %s --continue\""),
3232 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3234 return -1;
3237 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3239 struct lock_file todo_lock = LOCK_INIT;
3240 const char *todo_path = get_todo_path(opts);
3241 int next = todo_list->current, offset, fd;
3244 * rebase -i writes "git-rebase-todo" without the currently executing
3245 * command, appending it to "done" instead.
3247 if (is_rebase_i(opts))
3248 next++;
3250 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3251 if (fd < 0)
3252 return error_errno(_("could not lock '%s'"), todo_path);
3253 offset = get_item_line_offset(todo_list, next);
3254 if (write_in_full(fd, todo_list->buf.buf + offset,
3255 todo_list->buf.len - offset) < 0)
3256 return error_errno(_("could not write to '%s'"), todo_path);
3257 if (commit_lock_file(&todo_lock) < 0)
3258 return error(_("failed to finalize '%s'"), todo_path);
3260 if (is_rebase_i(opts) && next > 0) {
3261 const char *done = rebase_path_done();
3262 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3263 int ret = 0;
3265 if (fd < 0)
3266 return 0;
3267 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3268 get_item_line_length(todo_list, next - 1))
3269 < 0)
3270 ret = error_errno(_("could not write to '%s'"), done);
3271 if (close(fd) < 0)
3272 ret = error_errno(_("failed to finalize '%s'"), done);
3273 return ret;
3275 return 0;
3278 static int save_opts(struct replay_opts *opts)
3280 const char *opts_file = git_path_opts_file();
3281 int res = 0;
3283 if (opts->no_commit)
3284 res |= git_config_set_in_file_gently(opts_file,
3285 "options.no-commit", "true");
3286 if (opts->edit)
3287 res |= git_config_set_in_file_gently(opts_file,
3288 "options.edit", "true");
3289 if (opts->allow_empty)
3290 res |= git_config_set_in_file_gently(opts_file,
3291 "options.allow-empty", "true");
3292 if (opts->allow_empty_message)
3293 res |= git_config_set_in_file_gently(opts_file,
3294 "options.allow-empty-message", "true");
3295 if (opts->keep_redundant_commits)
3296 res |= git_config_set_in_file_gently(opts_file,
3297 "options.keep-redundant-commits", "true");
3298 if (opts->signoff)
3299 res |= git_config_set_in_file_gently(opts_file,
3300 "options.signoff", "true");
3301 if (opts->record_origin)
3302 res |= git_config_set_in_file_gently(opts_file,
3303 "options.record-origin", "true");
3304 if (opts->allow_ff)
3305 res |= git_config_set_in_file_gently(opts_file,
3306 "options.allow-ff", "true");
3307 if (opts->mainline) {
3308 struct strbuf buf = STRBUF_INIT;
3309 strbuf_addf(&buf, "%d", opts->mainline);
3310 res |= git_config_set_in_file_gently(opts_file,
3311 "options.mainline", buf.buf);
3312 strbuf_release(&buf);
3314 if (opts->strategy)
3315 res |= git_config_set_in_file_gently(opts_file,
3316 "options.strategy", opts->strategy);
3317 if (opts->gpg_sign)
3318 res |= git_config_set_in_file_gently(opts_file,
3319 "options.gpg-sign", opts->gpg_sign);
3320 if (opts->xopts) {
3321 int i;
3322 for (i = 0; i < opts->xopts_nr; i++)
3323 res |= git_config_set_multivar_in_file_gently(opts_file,
3324 "options.strategy-option",
3325 opts->xopts[i], "^$", 0);
3327 if (opts->allow_rerere_auto)
3328 res |= git_config_set_in_file_gently(opts_file,
3329 "options.allow-rerere-auto",
3330 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3331 "true" : "false");
3333 if (opts->explicit_cleanup)
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.default-msg-cleanup",
3336 describe_cleanup_mode(opts->default_msg_cleanup));
3337 return res;
3340 static int make_patch(struct repository *r,
3341 struct commit *commit,
3342 struct replay_opts *opts)
3344 struct strbuf buf = STRBUF_INIT;
3345 struct rev_info log_tree_opt;
3346 const char *subject;
3347 char hex[GIT_MAX_HEXSZ + 1];
3348 int res = 0;
3350 oid_to_hex_r(hex, &commit->object.oid);
3351 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3352 return -1;
3353 res |= write_rebase_head(&commit->object.oid);
3355 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3356 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3357 repo_init_revisions(r, &log_tree_opt, NULL);
3358 log_tree_opt.abbrev = 0;
3359 log_tree_opt.diff = 1;
3360 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3361 log_tree_opt.disable_stdin = 1;
3362 log_tree_opt.no_commit_id = 1;
3363 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3364 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3365 if (!log_tree_opt.diffopt.file)
3366 res |= error_errno(_("could not open '%s'"), buf.buf);
3367 else {
3368 res |= log_tree_commit(&log_tree_opt, commit);
3369 fclose(log_tree_opt.diffopt.file);
3371 strbuf_reset(&buf);
3373 strbuf_addf(&buf, "%s/message", get_dir(opts));
3374 if (!file_exists(buf.buf)) {
3375 const char *encoding = get_commit_output_encoding();
3376 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3377 find_commit_subject(commit_buffer, &subject);
3378 res |= write_message(subject, strlen(subject), buf.buf, 1);
3379 unuse_commit_buffer(commit, commit_buffer);
3381 strbuf_release(&buf);
3383 return res;
3386 static int intend_to_amend(void)
3388 struct object_id head;
3389 char *p;
3391 if (get_oid("HEAD", &head))
3392 return error(_("cannot read HEAD"));
3394 p = oid_to_hex(&head);
3395 return write_message(p, strlen(p), rebase_path_amend(), 1);
3398 static int error_with_patch(struct repository *r,
3399 struct commit *commit,
3400 const char *subject, int subject_len,
3401 struct replay_opts *opts,
3402 int exit_code, int to_amend)
3404 if (commit) {
3405 if (make_patch(r, commit, opts))
3406 return -1;
3407 } else if (copy_file(rebase_path_message(),
3408 git_path_merge_msg(r), 0666))
3409 return error(_("unable to copy '%s' to '%s'"),
3410 git_path_merge_msg(r), rebase_path_message());
3412 if (to_amend) {
3413 if (intend_to_amend())
3414 return -1;
3416 fprintf(stderr,
3417 _("You can amend the commit now, with\n"
3418 "\n"
3419 " git commit --amend %s\n"
3420 "\n"
3421 "Once you are satisfied with your changes, run\n"
3422 "\n"
3423 " git rebase --continue\n"),
3424 gpg_sign_opt_quoted(opts));
3425 } else if (exit_code) {
3426 if (commit)
3427 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3428 short_commit_name(commit), subject_len, subject);
3429 else
3431 * We don't have the hash of the parent so
3432 * just print the line from the todo file.
3434 fprintf_ln(stderr, _("Could not merge %.*s"),
3435 subject_len, subject);
3438 return exit_code;
3441 static int error_failed_squash(struct repository *r,
3442 struct commit *commit,
3443 struct replay_opts *opts,
3444 int subject_len,
3445 const char *subject)
3447 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3448 return error(_("could not copy '%s' to '%s'"),
3449 rebase_path_squash_msg(), rebase_path_message());
3450 unlink(git_path_merge_msg(r));
3451 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3452 return error(_("could not copy '%s' to '%s'"),
3453 rebase_path_message(),
3454 git_path_merge_msg(r));
3455 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3458 static int do_exec(struct repository *r, const char *command_line)
3460 struct strvec child_env = STRVEC_INIT;
3461 const char *child_argv[] = { NULL, NULL };
3462 int dirty, status;
3464 fprintf(stderr, _("Executing: %s\n"), command_line);
3465 child_argv[0] = command_line;
3466 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3467 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3468 absolute_path(get_git_work_tree()));
3469 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3470 child_env.v);
3472 /* force re-reading of the cache */
3473 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3474 return error(_("could not read index"));
3476 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3478 if (status) {
3479 warning(_("execution failed: %s\n%s"
3480 "You can fix the problem, and then run\n"
3481 "\n"
3482 " git rebase --continue\n"
3483 "\n"),
3484 command_line,
3485 dirty ? N_("and made changes to the index and/or the "
3486 "working tree\n") : "");
3487 if (status == 127)
3488 /* command not found */
3489 status = 1;
3490 } else if (dirty) {
3491 warning(_("execution succeeded: %s\nbut "
3492 "left changes to the index and/or the working tree\n"
3493 "Commit or stash your changes, and then run\n"
3494 "\n"
3495 " git rebase --continue\n"
3496 "\n"), command_line);
3497 status = 1;
3500 strvec_clear(&child_env);
3502 return status;
3505 static int safe_append(const char *filename, const char *fmt, ...)
3507 va_list ap;
3508 struct lock_file lock = LOCK_INIT;
3509 int fd = hold_lock_file_for_update(&lock, filename,
3510 LOCK_REPORT_ON_ERROR);
3511 struct strbuf buf = STRBUF_INIT;
3513 if (fd < 0)
3514 return -1;
3516 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3517 error_errno(_("could not read '%s'"), filename);
3518 rollback_lock_file(&lock);
3519 return -1;
3521 strbuf_complete(&buf, '\n');
3522 va_start(ap, fmt);
3523 strbuf_vaddf(&buf, fmt, ap);
3524 va_end(ap);
3526 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3527 error_errno(_("could not write to '%s'"), filename);
3528 strbuf_release(&buf);
3529 rollback_lock_file(&lock);
3530 return -1;
3532 if (commit_lock_file(&lock) < 0) {
3533 strbuf_release(&buf);
3534 rollback_lock_file(&lock);
3535 return error(_("failed to finalize '%s'"), filename);
3538 strbuf_release(&buf);
3539 return 0;
3542 static int do_label(struct repository *r, const char *name, int len)
3544 struct ref_store *refs = get_main_ref_store(r);
3545 struct ref_transaction *transaction;
3546 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3547 struct strbuf msg = STRBUF_INIT;
3548 int ret = 0;
3549 struct object_id head_oid;
3551 if (len == 1 && *name == '#')
3552 return error(_("illegal label name: '%.*s'"), len, name);
3554 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3555 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3557 transaction = ref_store_transaction_begin(refs, &err);
3558 if (!transaction) {
3559 error("%s", err.buf);
3560 ret = -1;
3561 } else if (get_oid("HEAD", &head_oid)) {
3562 error(_("could not read HEAD"));
3563 ret = -1;
3564 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3565 NULL, 0, msg.buf, &err) < 0 ||
3566 ref_transaction_commit(transaction, &err)) {
3567 error("%s", err.buf);
3568 ret = -1;
3570 ref_transaction_free(transaction);
3571 strbuf_release(&err);
3572 strbuf_release(&msg);
3574 if (!ret)
3575 ret = safe_append(rebase_path_refs_to_delete(),
3576 "%s\n", ref_name.buf);
3577 strbuf_release(&ref_name);
3579 return ret;
3582 static const char *reflog_message(struct replay_opts *opts,
3583 const char *sub_action, const char *fmt, ...);
3585 static int do_reset(struct repository *r,
3586 const char *name, int len,
3587 struct replay_opts *opts)
3589 struct strbuf ref_name = STRBUF_INIT;
3590 struct object_id oid;
3591 struct lock_file lock = LOCK_INIT;
3592 struct tree_desc desc;
3593 struct tree *tree;
3594 struct unpack_trees_options unpack_tree_opts;
3595 int ret = 0;
3597 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3598 return -1;
3600 if (len == 10 && !strncmp("[new root]", name, len)) {
3601 if (!opts->have_squash_onto) {
3602 const char *hex;
3603 if (commit_tree("", 0, the_hash_algo->empty_tree,
3604 NULL, &opts->squash_onto,
3605 NULL, NULL))
3606 return error(_("writing fake root commit"));
3607 opts->have_squash_onto = 1;
3608 hex = oid_to_hex(&opts->squash_onto);
3609 if (write_message(hex, strlen(hex),
3610 rebase_path_squash_onto(), 0))
3611 return error(_("writing squash-onto"));
3613 oidcpy(&oid, &opts->squash_onto);
3614 } else {
3615 int i;
3617 /* Determine the length of the label */
3618 for (i = 0; i < len; i++)
3619 if (isspace(name[i]))
3620 break;
3621 len = i;
3623 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3624 if (get_oid(ref_name.buf, &oid) &&
3625 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3626 error(_("could not read '%s'"), ref_name.buf);
3627 rollback_lock_file(&lock);
3628 strbuf_release(&ref_name);
3629 return -1;
3633 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3634 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3635 unpack_tree_opts.head_idx = 1;
3636 unpack_tree_opts.src_index = r->index;
3637 unpack_tree_opts.dst_index = r->index;
3638 unpack_tree_opts.fn = oneway_merge;
3639 unpack_tree_opts.merge = 1;
3640 unpack_tree_opts.update = 1;
3641 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3643 if (repo_read_index_unmerged(r)) {
3644 rollback_lock_file(&lock);
3645 strbuf_release(&ref_name);
3646 return error_resolve_conflict(_(action_name(opts)));
3649 if (!fill_tree_descriptor(r, &desc, &oid)) {
3650 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3651 rollback_lock_file(&lock);
3652 free((void *)desc.buffer);
3653 strbuf_release(&ref_name);
3654 return -1;
3657 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3658 rollback_lock_file(&lock);
3659 free((void *)desc.buffer);
3660 strbuf_release(&ref_name);
3661 return -1;
3664 tree = parse_tree_indirect(&oid);
3665 prime_cache_tree(r, r->index, tree);
3667 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3668 ret = error(_("could not write index"));
3669 free((void *)desc.buffer);
3671 if (!ret)
3672 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3673 len, name), "HEAD", &oid,
3674 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3676 strbuf_release(&ref_name);
3677 return ret;
3680 static struct commit *lookup_label(const char *label, int len,
3681 struct strbuf *buf)
3683 struct commit *commit;
3685 strbuf_reset(buf);
3686 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3687 commit = lookup_commit_reference_by_name(buf->buf);
3688 if (!commit) {
3689 /* fall back to non-rewritten ref or commit */
3690 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3691 commit = lookup_commit_reference_by_name(buf->buf);
3694 if (!commit)
3695 error(_("could not resolve '%s'"), buf->buf);
3697 return commit;
3700 static int do_merge(struct repository *r,
3701 struct commit *commit,
3702 const char *arg, int arg_len,
3703 int flags, struct replay_opts *opts)
3705 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3706 EDIT_MSG | VERIFY_MSG : 0;
3707 struct strbuf ref_name = STRBUF_INIT;
3708 struct commit *head_commit, *merge_commit, *i;
3709 struct commit_list *bases, *j, *reversed = NULL;
3710 struct commit_list *to_merge = NULL, **tail = &to_merge;
3711 const char *strategy = !opts->xopts_nr &&
3712 (!opts->strategy ||
3713 !strcmp(opts->strategy, "recursive") ||
3714 !strcmp(opts->strategy, "ort")) ?
3715 NULL : opts->strategy;
3716 struct merge_options o;
3717 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3718 static struct lock_file lock;
3719 const char *p;
3721 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3722 ret = -1;
3723 goto leave_merge;
3726 head_commit = lookup_commit_reference_by_name("HEAD");
3727 if (!head_commit) {
3728 ret = error(_("cannot merge without a current revision"));
3729 goto leave_merge;
3733 * For octopus merges, the arg starts with the list of revisions to be
3734 * merged. The list is optionally followed by '#' and the oneline.
3736 merge_arg_len = oneline_offset = arg_len;
3737 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3738 if (!*p)
3739 break;
3740 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3741 p += 1 + strspn(p + 1, " \t\n");
3742 oneline_offset = p - arg;
3743 break;
3745 k = strcspn(p, " \t\n");
3746 if (!k)
3747 continue;
3748 merge_commit = lookup_label(p, k, &ref_name);
3749 if (!merge_commit) {
3750 ret = error(_("unable to parse '%.*s'"), k, p);
3751 goto leave_merge;
3753 tail = &commit_list_insert(merge_commit, tail)->next;
3754 p += k;
3755 merge_arg_len = p - arg;
3758 if (!to_merge) {
3759 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3760 goto leave_merge;
3763 if (opts->have_squash_onto &&
3764 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3766 * When the user tells us to "merge" something into a
3767 * "[new root]", let's simply fast-forward to the merge head.
3769 rollback_lock_file(&lock);
3770 if (to_merge->next)
3771 ret = error(_("octopus merge cannot be executed on "
3772 "top of a [new root]"));
3773 else
3774 ret = fast_forward_to(r, &to_merge->item->object.oid,
3775 &head_commit->object.oid, 0,
3776 opts);
3777 goto leave_merge;
3780 if (commit) {
3781 const char *encoding = get_commit_output_encoding();
3782 const char *message = logmsg_reencode(commit, NULL, encoding);
3783 const char *body;
3784 int len;
3786 if (!message) {
3787 ret = error(_("could not get commit message of '%s'"),
3788 oid_to_hex(&commit->object.oid));
3789 goto leave_merge;
3791 write_author_script(message);
3792 find_commit_subject(message, &body);
3793 len = strlen(body);
3794 ret = write_message(body, len, git_path_merge_msg(r), 0);
3795 unuse_commit_buffer(commit, message);
3796 if (ret) {
3797 error_errno(_("could not write '%s'"),
3798 git_path_merge_msg(r));
3799 goto leave_merge;
3801 } else {
3802 struct strbuf buf = STRBUF_INIT;
3803 int len;
3805 strbuf_addf(&buf, "author %s", git_author_info(0));
3806 write_author_script(buf.buf);
3807 strbuf_reset(&buf);
3809 if (oneline_offset < arg_len) {
3810 p = arg + oneline_offset;
3811 len = arg_len - oneline_offset;
3812 } else {
3813 strbuf_addf(&buf, "Merge %s '%.*s'",
3814 to_merge->next ? "branches" : "branch",
3815 merge_arg_len, arg);
3816 p = buf.buf;
3817 len = buf.len;
3820 ret = write_message(p, len, git_path_merge_msg(r), 0);
3821 strbuf_release(&buf);
3822 if (ret) {
3823 error_errno(_("could not write '%s'"),
3824 git_path_merge_msg(r));
3825 goto leave_merge;
3830 * If HEAD is not identical to the first parent of the original merge
3831 * commit, we cannot fast-forward.
3833 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3834 oideq(&commit->parents->item->object.oid,
3835 &head_commit->object.oid);
3838 * If any merge head is different from the original one, we cannot
3839 * fast-forward.
3841 if (can_fast_forward) {
3842 struct commit_list *p = commit->parents->next;
3844 for (j = to_merge; j && p; j = j->next, p = p->next)
3845 if (!oideq(&j->item->object.oid,
3846 &p->item->object.oid)) {
3847 can_fast_forward = 0;
3848 break;
3851 * If the number of merge heads differs from the original merge
3852 * commit, we cannot fast-forward.
3854 if (j || p)
3855 can_fast_forward = 0;
3858 if (can_fast_forward) {
3859 rollback_lock_file(&lock);
3860 ret = fast_forward_to(r, &commit->object.oid,
3861 &head_commit->object.oid, 0, opts);
3862 if (flags & TODO_EDIT_MERGE_MSG) {
3863 run_commit_flags |= AMEND_MSG;
3864 goto fast_forward_edit;
3866 goto leave_merge;
3869 if (strategy || to_merge->next) {
3870 /* Octopus merge */
3871 struct child_process cmd = CHILD_PROCESS_INIT;
3873 if (read_env_script(&cmd.env_array)) {
3874 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3876 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3877 goto leave_merge;
3880 if (opts->committer_date_is_author_date)
3881 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3882 opts->ignore_date ?
3883 "" :
3884 author_date_from_env_array(&cmd.env_array));
3885 if (opts->ignore_date)
3886 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3888 cmd.git_cmd = 1;
3889 strvec_push(&cmd.args, "merge");
3890 strvec_push(&cmd.args, "-s");
3891 if (!strategy)
3892 strvec_push(&cmd.args, "octopus");
3893 else {
3894 strvec_push(&cmd.args, strategy);
3895 for (k = 0; k < opts->xopts_nr; k++)
3896 strvec_pushf(&cmd.args,
3897 "-X%s", opts->xopts[k]);
3899 strvec_push(&cmd.args, "--no-edit");
3900 strvec_push(&cmd.args, "--no-ff");
3901 strvec_push(&cmd.args, "--no-log");
3902 strvec_push(&cmd.args, "--no-stat");
3903 strvec_push(&cmd.args, "-F");
3904 strvec_push(&cmd.args, git_path_merge_msg(r));
3905 if (opts->gpg_sign)
3906 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3907 else
3908 strvec_push(&cmd.args, "--no-gpg-sign");
3910 /* Add the tips to be merged */
3911 for (j = to_merge; j; j = j->next)
3912 strvec_push(&cmd.args,
3913 oid_to_hex(&j->item->object.oid));
3915 strbuf_release(&ref_name);
3916 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3917 NULL, 0);
3918 rollback_lock_file(&lock);
3920 ret = run_command(&cmd);
3922 /* force re-reading of the cache */
3923 if (!ret && (discard_index(r->index) < 0 ||
3924 repo_read_index(r) < 0))
3925 ret = error(_("could not read index"));
3926 goto leave_merge;
3929 merge_commit = to_merge->item;
3930 bases = get_merge_bases(head_commit, merge_commit);
3931 if (bases && oideq(&merge_commit->object.oid,
3932 &bases->item->object.oid)) {
3933 ret = 0;
3934 /* skip merging an ancestor of HEAD */
3935 goto leave_merge;
3938 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3939 git_path_merge_head(r), 0);
3940 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3942 for (j = bases; j; j = j->next)
3943 commit_list_insert(j->item, &reversed);
3944 free_commit_list(bases);
3946 repo_read_index(r);
3947 init_merge_options(&o, r);
3948 o.branch1 = "HEAD";
3949 o.branch2 = ref_name.buf;
3950 o.buffer_output = 2;
3952 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3954 * TODO: Should use merge_incore_recursive() and
3955 * merge_switch_to_result(), skipping the call to
3956 * merge_switch_to_result() when we don't actually need to
3957 * update the index and working copy immediately.
3959 ret = merge_ort_recursive(&o,
3960 head_commit, merge_commit, reversed,
3961 &i);
3962 } else {
3963 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3964 &i);
3966 if (ret <= 0)
3967 fputs(o.obuf.buf, stdout);
3968 strbuf_release(&o.obuf);
3969 if (ret < 0) {
3970 error(_("could not even attempt to merge '%.*s'"),
3971 merge_arg_len, arg);
3972 goto leave_merge;
3975 * The return value of merge_recursive() is 1 on clean, and 0 on
3976 * unclean merge.
3978 * Let's reverse that, so that do_merge() returns 0 upon success and
3979 * 1 upon failed merge (keeping the return value -1 for the cases where
3980 * we will want to reschedule the `merge` command).
3982 ret = !ret;
3984 if (r->index->cache_changed &&
3985 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3986 ret = error(_("merge: Unable to write new index file"));
3987 goto leave_merge;
3990 rollback_lock_file(&lock);
3991 if (ret)
3992 repo_rerere(r, opts->allow_rerere_auto);
3993 else
3995 * In case of problems, we now want to return a positive
3996 * value (a negative one would indicate that the `merge`
3997 * command needs to be rescheduled).
3999 fast_forward_edit:
4000 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4001 run_commit_flags);
4003 leave_merge:
4004 strbuf_release(&ref_name);
4005 rollback_lock_file(&lock);
4006 free_commit_list(to_merge);
4007 return ret;
4010 static int is_final_fixup(struct todo_list *todo_list)
4012 int i = todo_list->current;
4014 if (!is_fixup(todo_list->items[i].command))
4015 return 0;
4017 while (++i < todo_list->nr)
4018 if (is_fixup(todo_list->items[i].command))
4019 return 0;
4020 else if (!is_noop(todo_list->items[i].command))
4021 break;
4022 return 1;
4025 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4027 int i;
4029 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4030 if (!is_noop(todo_list->items[i].command))
4031 return todo_list->items[i].command;
4033 return -1;
4036 void create_autostash(struct repository *r, const char *path,
4037 const char *default_reflog_action)
4039 struct strbuf buf = STRBUF_INIT;
4040 struct lock_file lock_file = LOCK_INIT;
4041 int fd;
4043 fd = repo_hold_locked_index(r, &lock_file, 0);
4044 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4045 if (0 <= fd)
4046 repo_update_index_if_able(r, &lock_file);
4047 rollback_lock_file(&lock_file);
4049 if (has_unstaged_changes(r, 1) ||
4050 has_uncommitted_changes(r, 1)) {
4051 struct child_process stash = CHILD_PROCESS_INIT;
4052 struct object_id oid;
4054 strvec_pushl(&stash.args,
4055 "stash", "create", "autostash", NULL);
4056 stash.git_cmd = 1;
4057 stash.no_stdin = 1;
4058 strbuf_reset(&buf);
4059 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4060 die(_("Cannot autostash"));
4061 strbuf_trim_trailing_newline(&buf);
4062 if (get_oid(buf.buf, &oid))
4063 die(_("Unexpected stash response: '%s'"),
4064 buf.buf);
4065 strbuf_reset(&buf);
4066 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4068 if (safe_create_leading_directories_const(path))
4069 die(_("Could not create directory for '%s'"),
4070 path);
4071 write_file(path, "%s", oid_to_hex(&oid));
4072 printf(_("Created autostash: %s\n"), buf.buf);
4073 if (reset_head(r, NULL, "reset --hard",
4074 NULL, RESET_HEAD_HARD, NULL, NULL,
4075 default_reflog_action) < 0)
4076 die(_("could not reset --hard"));
4078 if (discard_index(r->index) < 0 ||
4079 repo_read_index(r) < 0)
4080 die(_("could not read index"));
4082 strbuf_release(&buf);
4085 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4087 struct child_process child = CHILD_PROCESS_INIT;
4088 int ret = 0;
4090 if (attempt_apply) {
4091 child.git_cmd = 1;
4092 child.no_stdout = 1;
4093 child.no_stderr = 1;
4094 strvec_push(&child.args, "stash");
4095 strvec_push(&child.args, "apply");
4096 strvec_push(&child.args, stash_oid);
4097 ret = run_command(&child);
4100 if (attempt_apply && !ret)
4101 fprintf(stderr, _("Applied autostash.\n"));
4102 else {
4103 struct child_process store = CHILD_PROCESS_INIT;
4105 store.git_cmd = 1;
4106 strvec_push(&store.args, "stash");
4107 strvec_push(&store.args, "store");
4108 strvec_push(&store.args, "-m");
4109 strvec_push(&store.args, "autostash");
4110 strvec_push(&store.args, "-q");
4111 strvec_push(&store.args, stash_oid);
4112 if (run_command(&store))
4113 ret = error(_("cannot store %s"), stash_oid);
4114 else
4115 fprintf(stderr,
4116 _("%s\n"
4117 "Your changes are safe in the stash.\n"
4118 "You can run \"git stash pop\" or"
4119 " \"git stash drop\" at any time.\n"),
4120 attempt_apply ?
4121 _("Applying autostash resulted in conflicts.") :
4122 _("Autostash exists; creating a new stash entry."));
4125 return ret;
4128 static int apply_save_autostash(const char *path, int attempt_apply)
4130 struct strbuf stash_oid = STRBUF_INIT;
4131 int ret = 0;
4133 if (!read_oneliner(&stash_oid, path,
4134 READ_ONELINER_SKIP_IF_EMPTY)) {
4135 strbuf_release(&stash_oid);
4136 return 0;
4138 strbuf_trim(&stash_oid);
4140 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4142 unlink(path);
4143 strbuf_release(&stash_oid);
4144 return ret;
4147 int save_autostash(const char *path)
4149 return apply_save_autostash(path, 0);
4152 int apply_autostash(const char *path)
4154 return apply_save_autostash(path, 1);
4157 int apply_autostash_oid(const char *stash_oid)
4159 return apply_save_autostash_oid(stash_oid, 1);
4162 static const char *reflog_message(struct replay_opts *opts,
4163 const char *sub_action, const char *fmt, ...)
4165 va_list ap;
4166 static struct strbuf buf = STRBUF_INIT;
4167 char *reflog_action = getenv(GIT_REFLOG_ACTION);
4169 va_start(ap, fmt);
4170 strbuf_reset(&buf);
4171 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4172 if (sub_action)
4173 strbuf_addf(&buf, " (%s)", sub_action);
4174 if (fmt) {
4175 strbuf_addstr(&buf, ": ");
4176 strbuf_vaddf(&buf, fmt, ap);
4178 va_end(ap);
4180 return buf.buf;
4183 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4184 const char *commit, const char *action)
4186 struct child_process cmd = CHILD_PROCESS_INIT;
4187 int ret;
4189 cmd.git_cmd = 1;
4191 strvec_push(&cmd.args, "checkout");
4192 strvec_push(&cmd.args, commit);
4193 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4195 if (opts->verbose)
4196 ret = run_command(&cmd);
4197 else
4198 ret = run_command_silent_on_success(&cmd);
4200 if (!ret)
4201 discard_index(r->index);
4203 return ret;
4206 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4207 const char *onto_name, const struct object_id *onto,
4208 const struct object_id *orig_head)
4210 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4212 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4213 apply_autostash(rebase_path_autostash());
4214 sequencer_remove_state(opts);
4215 return error(_("could not detach HEAD"));
4218 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4221 static int stopped_at_head(struct repository *r)
4223 struct object_id head;
4224 struct commit *commit;
4225 struct commit_message message;
4227 if (get_oid("HEAD", &head) ||
4228 !(commit = lookup_commit(r, &head)) ||
4229 parse_commit(commit) || get_message(commit, &message))
4230 fprintf(stderr, _("Stopped at HEAD\n"));
4231 else {
4232 fprintf(stderr, _("Stopped at %s\n"), message.label);
4233 free_message(commit, &message);
4235 return 0;
4239 static const char rescheduled_advice[] =
4240 N_("Could not execute the todo command\n"
4241 "\n"
4242 " %.*s"
4243 "\n"
4244 "It has been rescheduled; To edit the command before continuing, please\n"
4245 "edit the todo list first:\n"
4246 "\n"
4247 " git rebase --edit-todo\n"
4248 " git rebase --continue\n");
4250 static int pick_commits(struct repository *r,
4251 struct todo_list *todo_list,
4252 struct replay_opts *opts)
4254 int res = 0, reschedule = 0;
4255 char *prev_reflog_action;
4257 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4258 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4259 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4260 if (opts->allow_ff)
4261 assert(!(opts->signoff || opts->no_commit ||
4262 opts->record_origin || opts->edit ||
4263 opts->committer_date_is_author_date ||
4264 opts->ignore_date));
4265 if (read_and_refresh_cache(r, opts))
4266 return -1;
4268 while (todo_list->current < todo_list->nr) {
4269 struct todo_item *item = todo_list->items + todo_list->current;
4270 const char *arg = todo_item_get_arg(todo_list, item);
4271 int check_todo = 0;
4273 if (save_todo(todo_list, opts))
4274 return -1;
4275 if (is_rebase_i(opts)) {
4276 if (item->command != TODO_COMMENT) {
4277 FILE *f = fopen(rebase_path_msgnum(), "w");
4279 todo_list->done_nr++;
4281 if (f) {
4282 fprintf(f, "%d\n", todo_list->done_nr);
4283 fclose(f);
4285 if (!opts->quiet)
4286 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4287 todo_list->done_nr,
4288 todo_list->total_nr,
4289 opts->verbose ? "\n" : "\r");
4291 unlink(rebase_path_message());
4292 unlink(rebase_path_author_script());
4293 unlink(rebase_path_stopped_sha());
4294 unlink(rebase_path_amend());
4295 unlink(git_path_merge_head(r));
4296 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4298 if (item->command == TODO_BREAK) {
4299 if (!opts->verbose)
4300 term_clear_line();
4301 return stopped_at_head(r);
4304 if (item->command <= TODO_SQUASH) {
4305 if (is_rebase_i(opts))
4306 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4307 command_to_string(item->command), NULL),
4309 res = do_pick_commit(r, item, opts,
4310 is_final_fixup(todo_list),
4311 &check_todo);
4312 if (is_rebase_i(opts))
4313 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4314 if (is_rebase_i(opts) && res < 0) {
4315 /* Reschedule */
4316 advise(_(rescheduled_advice),
4317 get_item_line_length(todo_list,
4318 todo_list->current),
4319 get_item_line(todo_list,
4320 todo_list->current));
4321 todo_list->current--;
4322 if (save_todo(todo_list, opts))
4323 return -1;
4325 if (item->command == TODO_EDIT) {
4326 struct commit *commit = item->commit;
4327 if (!res) {
4328 if (!opts->verbose)
4329 term_clear_line();
4330 fprintf(stderr,
4331 _("Stopped at %s... %.*s\n"),
4332 short_commit_name(commit),
4333 item->arg_len, arg);
4335 return error_with_patch(r, commit,
4336 arg, item->arg_len, opts, res, !res);
4338 if (is_rebase_i(opts) && !res)
4339 record_in_rewritten(&item->commit->object.oid,
4340 peek_command(todo_list, 1));
4341 if (res && is_fixup(item->command)) {
4342 if (res == 1)
4343 intend_to_amend();
4344 return error_failed_squash(r, item->commit, opts,
4345 item->arg_len, arg);
4346 } else if (res && is_rebase_i(opts) && item->commit) {
4347 int to_amend = 0;
4348 struct object_id oid;
4351 * If we are rewording and have either
4352 * fast-forwarded already, or are about to
4353 * create a new root commit, we want to amend,
4354 * otherwise we do not.
4356 if (item->command == TODO_REWORD &&
4357 !get_oid("HEAD", &oid) &&
4358 (oideq(&item->commit->object.oid, &oid) ||
4359 (opts->have_squash_onto &&
4360 oideq(&opts->squash_onto, &oid))))
4361 to_amend = 1;
4363 return res | error_with_patch(r, item->commit,
4364 arg, item->arg_len, opts,
4365 res, to_amend);
4367 } else if (item->command == TODO_EXEC) {
4368 char *end_of_arg = (char *)(arg + item->arg_len);
4369 int saved = *end_of_arg;
4371 if (!opts->verbose)
4372 term_clear_line();
4373 *end_of_arg = '\0';
4374 res = do_exec(r, arg);
4375 *end_of_arg = saved;
4377 if (res) {
4378 if (opts->reschedule_failed_exec)
4379 reschedule = 1;
4381 check_todo = 1;
4382 } else if (item->command == TODO_LABEL) {
4383 if ((res = do_label(r, arg, item->arg_len)))
4384 reschedule = 1;
4385 } else if (item->command == TODO_RESET) {
4386 if ((res = do_reset(r, arg, item->arg_len, opts)))
4387 reschedule = 1;
4388 } else if (item->command == TODO_MERGE) {
4389 if ((res = do_merge(r, item->commit,
4390 arg, item->arg_len,
4391 item->flags, opts)) < 0)
4392 reschedule = 1;
4393 else if (item->commit)
4394 record_in_rewritten(&item->commit->object.oid,
4395 peek_command(todo_list, 1));
4396 if (res > 0)
4397 /* failed with merge conflicts */
4398 return error_with_patch(r, item->commit,
4399 arg, item->arg_len,
4400 opts, res, 0);
4401 } else if (!is_noop(item->command))
4402 return error(_("unknown command %d"), item->command);
4404 if (reschedule) {
4405 advise(_(rescheduled_advice),
4406 get_item_line_length(todo_list,
4407 todo_list->current),
4408 get_item_line(todo_list, todo_list->current));
4409 todo_list->current--;
4410 if (save_todo(todo_list, opts))
4411 return -1;
4412 if (item->commit)
4413 return error_with_patch(r,
4414 item->commit,
4415 arg, item->arg_len,
4416 opts, res, 0);
4417 } else if (is_rebase_i(opts) && check_todo && !res) {
4418 struct stat st;
4420 if (stat(get_todo_path(opts), &st)) {
4421 res = error_errno(_("could not stat '%s'"),
4422 get_todo_path(opts));
4423 } else if (match_stat_data(&todo_list->stat, &st)) {
4424 /* Reread the todo file if it has changed. */
4425 todo_list_release(todo_list);
4426 if (read_populate_todo(r, todo_list, opts))
4427 res = -1; /* message was printed */
4428 /* `current` will be incremented below */
4429 todo_list->current = -1;
4433 todo_list->current++;
4434 if (res)
4435 return res;
4438 if (is_rebase_i(opts)) {
4439 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4440 struct stat st;
4442 /* Stopped in the middle, as planned? */
4443 if (todo_list->current < todo_list->nr)
4444 return 0;
4446 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4447 starts_with(head_ref.buf, "refs/")) {
4448 const char *msg;
4449 struct object_id head, orig;
4450 int res;
4452 if (get_oid("HEAD", &head)) {
4453 res = error(_("cannot read HEAD"));
4454 cleanup_head_ref:
4455 strbuf_release(&head_ref);
4456 strbuf_release(&buf);
4457 return res;
4459 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4460 get_oid_hex(buf.buf, &orig)) {
4461 res = error(_("could not read orig-head"));
4462 goto cleanup_head_ref;
4464 strbuf_reset(&buf);
4465 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4466 res = error(_("could not read 'onto'"));
4467 goto cleanup_head_ref;
4469 msg = reflog_message(opts, "finish", "%s onto %s",
4470 head_ref.buf, buf.buf);
4471 if (update_ref(msg, head_ref.buf, &head, &orig,
4472 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4473 res = error(_("could not update %s"),
4474 head_ref.buf);
4475 goto cleanup_head_ref;
4477 msg = reflog_message(opts, "finish", "returning to %s",
4478 head_ref.buf);
4479 if (create_symref("HEAD", head_ref.buf, msg)) {
4480 res = error(_("could not update HEAD to %s"),
4481 head_ref.buf);
4482 goto cleanup_head_ref;
4484 strbuf_reset(&buf);
4487 if (opts->verbose) {
4488 struct rev_info log_tree_opt;
4489 struct object_id orig, head;
4491 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4492 repo_init_revisions(r, &log_tree_opt, NULL);
4493 log_tree_opt.diff = 1;
4494 log_tree_opt.diffopt.output_format =
4495 DIFF_FORMAT_DIFFSTAT;
4496 log_tree_opt.disable_stdin = 1;
4498 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4499 !get_oid(buf.buf, &orig) &&
4500 !get_oid("HEAD", &head)) {
4501 diff_tree_oid(&orig, &head, "",
4502 &log_tree_opt.diffopt);
4503 log_tree_diff_flush(&log_tree_opt);
4506 flush_rewritten_pending();
4507 if (!stat(rebase_path_rewritten_list(), &st) &&
4508 st.st_size > 0) {
4509 struct child_process child = CHILD_PROCESS_INIT;
4510 const char *post_rewrite_hook =
4511 find_hook("post-rewrite");
4513 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4514 child.git_cmd = 1;
4515 strvec_push(&child.args, "notes");
4516 strvec_push(&child.args, "copy");
4517 strvec_push(&child.args, "--for-rewrite=rebase");
4518 /* we don't care if this copying failed */
4519 run_command(&child);
4521 if (post_rewrite_hook) {
4522 struct child_process hook = CHILD_PROCESS_INIT;
4524 hook.in = open(rebase_path_rewritten_list(),
4525 O_RDONLY);
4526 hook.stdout_to_stderr = 1;
4527 hook.trace2_hook_name = "post-rewrite";
4528 strvec_push(&hook.args, post_rewrite_hook);
4529 strvec_push(&hook.args, "rebase");
4530 /* we don't care if this hook failed */
4531 run_command(&hook);
4534 apply_autostash(rebase_path_autostash());
4536 if (!opts->quiet) {
4537 if (!opts->verbose)
4538 term_clear_line();
4539 fprintf(stderr,
4540 _("Successfully rebased and updated %s.\n"),
4541 head_ref.buf);
4544 strbuf_release(&buf);
4545 strbuf_release(&head_ref);
4549 * Sequence of picks finished successfully; cleanup by
4550 * removing the .git/sequencer directory
4552 return sequencer_remove_state(opts);
4555 static int continue_single_pick(struct repository *r)
4557 const char *argv[] = { "commit", NULL };
4559 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4560 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4561 return error(_("no cherry-pick or revert in progress"));
4562 return run_command_v_opt(argv, RUN_GIT_CMD);
4565 static int commit_staged_changes(struct repository *r,
4566 struct replay_opts *opts,
4567 struct todo_list *todo_list)
4569 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4570 unsigned int final_fixup = 0, is_clean;
4572 if (has_unstaged_changes(r, 1))
4573 return error(_("cannot rebase: You have unstaged changes."));
4575 is_clean = !has_uncommitted_changes(r, 0);
4577 if (file_exists(rebase_path_amend())) {
4578 struct strbuf rev = STRBUF_INIT;
4579 struct object_id head, to_amend;
4581 if (get_oid("HEAD", &head))
4582 return error(_("cannot amend non-existing commit"));
4583 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4584 return error(_("invalid file: '%s'"), rebase_path_amend());
4585 if (get_oid_hex(rev.buf, &to_amend))
4586 return error(_("invalid contents: '%s'"),
4587 rebase_path_amend());
4588 if (!is_clean && !oideq(&head, &to_amend))
4589 return error(_("\nYou have uncommitted changes in your "
4590 "working tree. Please, commit them\n"
4591 "first and then run 'git rebase "
4592 "--continue' again."));
4594 * When skipping a failed fixup/squash, we need to edit the
4595 * commit message, the current fixup list and count, and if it
4596 * was the last fixup/squash in the chain, we need to clean up
4597 * the commit message and if there was a squash, let the user
4598 * edit it.
4600 if (!is_clean || !opts->current_fixup_count)
4601 ; /* this is not the final fixup */
4602 else if (!oideq(&head, &to_amend) ||
4603 !file_exists(rebase_path_stopped_sha())) {
4604 /* was a final fixup or squash done manually? */
4605 if (!is_fixup(peek_command(todo_list, 0))) {
4606 unlink(rebase_path_fixup_msg());
4607 unlink(rebase_path_squash_msg());
4608 unlink(rebase_path_current_fixups());
4609 strbuf_reset(&opts->current_fixups);
4610 opts->current_fixup_count = 0;
4612 } else {
4613 /* we are in a fixup/squash chain */
4614 const char *p = opts->current_fixups.buf;
4615 int len = opts->current_fixups.len;
4617 opts->current_fixup_count--;
4618 if (!len)
4619 BUG("Incorrect current_fixups:\n%s", p);
4620 while (len && p[len - 1] != '\n')
4621 len--;
4622 strbuf_setlen(&opts->current_fixups, len);
4623 if (write_message(p, len, rebase_path_current_fixups(),
4624 0) < 0)
4625 return error(_("could not write file: '%s'"),
4626 rebase_path_current_fixups());
4629 * If a fixup/squash in a fixup/squash chain failed, the
4630 * commit message is already correct, no need to commit
4631 * it again.
4633 * Only if it is the final command in the fixup/squash
4634 * chain, and only if the chain is longer than a single
4635 * fixup/squash command (which was just skipped), do we
4636 * actually need to re-commit with a cleaned up commit
4637 * message.
4639 if (opts->current_fixup_count > 0 &&
4640 !is_fixup(peek_command(todo_list, 0))) {
4641 final_fixup = 1;
4643 * If there was not a single "squash" in the
4644 * chain, we only need to clean up the commit
4645 * message, no need to bother the user with
4646 * opening the commit message in the editor.
4648 if (!starts_with(p, "squash ") &&
4649 !strstr(p, "\nsquash "))
4650 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4651 } else if (is_fixup(peek_command(todo_list, 0))) {
4653 * We need to update the squash message to skip
4654 * the latest commit message.
4656 struct commit *commit;
4657 const char *path = rebase_path_squash_msg();
4658 const char *encoding = get_commit_output_encoding();
4660 if (parse_head(r, &commit) ||
4661 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4662 write_message(p, strlen(p), path, 0)) {
4663 unuse_commit_buffer(commit, p);
4664 return error(_("could not write file: "
4665 "'%s'"), path);
4667 unuse_commit_buffer(commit, p);
4671 strbuf_release(&rev);
4672 flags |= AMEND_MSG;
4675 if (is_clean) {
4676 if (refs_ref_exists(get_main_ref_store(r),
4677 "CHERRY_PICK_HEAD") &&
4678 refs_delete_ref(get_main_ref_store(r), "",
4679 "CHERRY_PICK_HEAD", NULL, 0))
4680 return error(_("could not remove CHERRY_PICK_HEAD"));
4681 if (!final_fixup)
4682 return 0;
4685 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4686 opts, flags))
4687 return error(_("could not commit staged changes."));
4688 unlink(rebase_path_amend());
4689 unlink(git_path_merge_head(r));
4690 if (final_fixup) {
4691 unlink(rebase_path_fixup_msg());
4692 unlink(rebase_path_squash_msg());
4694 if (opts->current_fixup_count > 0) {
4696 * Whether final fixup or not, we just cleaned up the commit
4697 * message...
4699 unlink(rebase_path_current_fixups());
4700 strbuf_reset(&opts->current_fixups);
4701 opts->current_fixup_count = 0;
4703 return 0;
4706 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4708 struct todo_list todo_list = TODO_LIST_INIT;
4709 int res;
4711 if (read_and_refresh_cache(r, opts))
4712 return -1;
4714 if (read_populate_opts(opts))
4715 return -1;
4716 if (is_rebase_i(opts)) {
4717 if ((res = read_populate_todo(r, &todo_list, opts)))
4718 goto release_todo_list;
4720 if (file_exists(rebase_path_dropped())) {
4721 if ((res = todo_list_check_against_backup(r, &todo_list)))
4722 goto release_todo_list;
4724 unlink(rebase_path_dropped());
4727 if (commit_staged_changes(r, opts, &todo_list)) {
4728 res = -1;
4729 goto release_todo_list;
4731 } else if (!file_exists(get_todo_path(opts)))
4732 return continue_single_pick(r);
4733 else if ((res = read_populate_todo(r, &todo_list, opts)))
4734 goto release_todo_list;
4736 if (!is_rebase_i(opts)) {
4737 /* Verify that the conflict has been resolved */
4738 if (refs_ref_exists(get_main_ref_store(r),
4739 "CHERRY_PICK_HEAD") ||
4740 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4741 res = continue_single_pick(r);
4742 if (res)
4743 goto release_todo_list;
4745 if (index_differs_from(r, "HEAD", NULL, 0)) {
4746 res = error_dirty_index(r, opts);
4747 goto release_todo_list;
4749 todo_list.current++;
4750 } else if (file_exists(rebase_path_stopped_sha())) {
4751 struct strbuf buf = STRBUF_INIT;
4752 struct object_id oid;
4754 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4755 READ_ONELINER_SKIP_IF_EMPTY) &&
4756 !get_oid_hex(buf.buf, &oid))
4757 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4758 strbuf_release(&buf);
4761 res = pick_commits(r, &todo_list, opts);
4762 release_todo_list:
4763 todo_list_release(&todo_list);
4764 return res;
4767 static int single_pick(struct repository *r,
4768 struct commit *cmit,
4769 struct replay_opts *opts)
4771 int check_todo;
4772 struct todo_item item;
4774 item.command = opts->action == REPLAY_PICK ?
4775 TODO_PICK : TODO_REVERT;
4776 item.commit = cmit;
4778 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4779 return do_pick_commit(r, &item, opts, 0, &check_todo);
4782 int sequencer_pick_revisions(struct repository *r,
4783 struct replay_opts *opts)
4785 struct todo_list todo_list = TODO_LIST_INIT;
4786 struct object_id oid;
4787 int i, res;
4789 assert(opts->revs);
4790 if (read_and_refresh_cache(r, opts))
4791 return -1;
4793 for (i = 0; i < opts->revs->pending.nr; i++) {
4794 struct object_id oid;
4795 const char *name = opts->revs->pending.objects[i].name;
4797 /* This happens when using --stdin. */
4798 if (!strlen(name))
4799 continue;
4801 if (!get_oid(name, &oid)) {
4802 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4803 enum object_type type = oid_object_info(r,
4804 &oid,
4805 NULL);
4806 return error(_("%s: can't cherry-pick a %s"),
4807 name, type_name(type));
4809 } else
4810 return error(_("%s: bad revision"), name);
4814 * If we were called as "git cherry-pick <commit>", just
4815 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4816 * REVERT_HEAD, and don't touch the sequencer state.
4817 * This means it is possible to cherry-pick in the middle
4818 * of a cherry-pick sequence.
4820 if (opts->revs->cmdline.nr == 1 &&
4821 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4822 opts->revs->no_walk &&
4823 !opts->revs->cmdline.rev->flags) {
4824 struct commit *cmit;
4825 if (prepare_revision_walk(opts->revs))
4826 return error(_("revision walk setup failed"));
4827 cmit = get_revision(opts->revs);
4828 if (!cmit)
4829 return error(_("empty commit set passed"));
4830 if (get_revision(opts->revs))
4831 BUG("unexpected extra commit from walk");
4832 return single_pick(r, cmit, opts);
4836 * Start a new cherry-pick/ revert sequence; but
4837 * first, make sure that an existing one isn't in
4838 * progress
4841 if (walk_revs_populate_todo(&todo_list, opts) ||
4842 create_seq_dir(r) < 0)
4843 return -1;
4844 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4845 return error(_("can't revert as initial commit"));
4846 if (save_head(oid_to_hex(&oid)))
4847 return -1;
4848 if (save_opts(opts))
4849 return -1;
4850 update_abort_safety_file();
4851 res = pick_commits(r, &todo_list, opts);
4852 todo_list_release(&todo_list);
4853 return res;
4856 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4858 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4859 struct strbuf sob = STRBUF_INIT;
4860 int has_footer;
4862 strbuf_addstr(&sob, sign_off_header);
4863 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4864 strbuf_addch(&sob, '\n');
4866 if (!ignore_footer)
4867 strbuf_complete_line(msgbuf);
4870 * If the whole message buffer is equal to the sob, pretend that we
4871 * found a conforming footer with a matching sob
4873 if (msgbuf->len - ignore_footer == sob.len &&
4874 !strncmp(msgbuf->buf, sob.buf, sob.len))
4875 has_footer = 3;
4876 else
4877 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4879 if (!has_footer) {
4880 const char *append_newlines = NULL;
4881 size_t len = msgbuf->len - ignore_footer;
4883 if (!len) {
4885 * The buffer is completely empty. Leave foom for
4886 * the title and body to be filled in by the user.
4888 append_newlines = "\n\n";
4889 } else if (len == 1) {
4891 * Buffer contains a single newline. Add another
4892 * so that we leave room for the title and body.
4894 append_newlines = "\n";
4895 } else if (msgbuf->buf[len - 2] != '\n') {
4897 * Buffer ends with a single newline. Add another
4898 * so that there is an empty line between the message
4899 * body and the sob.
4901 append_newlines = "\n";
4902 } /* else, the buffer already ends with two newlines. */
4904 if (append_newlines)
4905 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4906 append_newlines, strlen(append_newlines));
4909 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4910 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4911 sob.buf, sob.len);
4913 strbuf_release(&sob);
4916 struct labels_entry {
4917 struct hashmap_entry entry;
4918 char label[FLEX_ARRAY];
4921 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4922 const struct hashmap_entry *entry_or_key, const void *key)
4924 const struct labels_entry *a, *b;
4926 a = container_of(eptr, const struct labels_entry, entry);
4927 b = container_of(entry_or_key, const struct labels_entry, entry);
4929 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4932 struct string_entry {
4933 struct oidmap_entry entry;
4934 char string[FLEX_ARRAY];
4937 struct label_state {
4938 struct oidmap commit2label;
4939 struct hashmap labels;
4940 struct strbuf buf;
4943 static const char *label_oid(struct object_id *oid, const char *label,
4944 struct label_state *state)
4946 struct labels_entry *labels_entry;
4947 struct string_entry *string_entry;
4948 struct object_id dummy;
4949 int i;
4951 string_entry = oidmap_get(&state->commit2label, oid);
4952 if (string_entry)
4953 return string_entry->string;
4956 * For "uninteresting" commits, i.e. commits that are not to be
4957 * rebased, and which can therefore not be labeled, we use a unique
4958 * abbreviation of the commit name. This is slightly more complicated
4959 * than calling find_unique_abbrev() because we also need to make
4960 * sure that the abbreviation does not conflict with any other
4961 * label.
4963 * We disallow "interesting" commits to be labeled by a string that
4964 * is a valid full-length hash, to ensure that we always can find an
4965 * abbreviation for any uninteresting commit's names that does not
4966 * clash with any other label.
4968 strbuf_reset(&state->buf);
4969 if (!label) {
4970 char *p;
4972 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4973 label = p = state->buf.buf;
4975 find_unique_abbrev_r(p, oid, default_abbrev);
4978 * We may need to extend the abbreviated hash so that there is
4979 * no conflicting label.
4981 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4982 size_t i = strlen(p) + 1;
4984 oid_to_hex_r(p, oid);
4985 for (; i < the_hash_algo->hexsz; i++) {
4986 char save = p[i];
4987 p[i] = '\0';
4988 if (!hashmap_get_from_hash(&state->labels,
4989 strihash(p), p))
4990 break;
4991 p[i] = save;
4994 } else {
4995 struct strbuf *buf = &state->buf;
4998 * Sanitize labels by replacing non-alpha-numeric characters
4999 * (including white-space ones) by dashes, as they might be
5000 * illegal in file names (and hence in ref names).
5002 * Note that we retain non-ASCII UTF-8 characters (identified
5003 * via the most significant bit). They should be all acceptable
5004 * in file names. We do not validate the UTF-8 here, that's not
5005 * the job of this function.
5007 for (; *label; label++)
5008 if ((*label & 0x80) || isalnum(*label))
5009 strbuf_addch(buf, *label);
5010 /* avoid leading dash and double-dashes */
5011 else if (buf->len && buf->buf[buf->len - 1] != '-')
5012 strbuf_addch(buf, '-');
5013 if (!buf->len) {
5014 strbuf_addstr(buf, "rev-");
5015 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5017 label = buf->buf;
5019 if ((buf->len == the_hash_algo->hexsz &&
5020 !get_oid_hex(label, &dummy)) ||
5021 (buf->len == 1 && *label == '#') ||
5022 hashmap_get_from_hash(&state->labels,
5023 strihash(label), label)) {
5025 * If the label already exists, or if the label is a
5026 * valid full OID, or the label is a '#' (which we use
5027 * as a separator between merge heads and oneline), we
5028 * append a dash and a number to make it unique.
5030 size_t len = buf->len;
5032 for (i = 2; ; i++) {
5033 strbuf_setlen(buf, len);
5034 strbuf_addf(buf, "-%d", i);
5035 if (!hashmap_get_from_hash(&state->labels,
5036 strihash(buf->buf),
5037 buf->buf))
5038 break;
5041 label = buf->buf;
5045 FLEX_ALLOC_STR(labels_entry, label, label);
5046 hashmap_entry_init(&labels_entry->entry, strihash(label));
5047 hashmap_add(&state->labels, &labels_entry->entry);
5049 FLEX_ALLOC_STR(string_entry, string, label);
5050 oidcpy(&string_entry->entry.oid, oid);
5051 oidmap_put(&state->commit2label, string_entry);
5053 return string_entry->string;
5056 static int make_script_with_merges(struct pretty_print_context *pp,
5057 struct rev_info *revs, struct strbuf *out,
5058 unsigned flags)
5060 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5061 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5062 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5063 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5064 struct strbuf label = STRBUF_INIT;
5065 struct commit_list *commits = NULL, **tail = &commits, *iter;
5066 struct commit_list *tips = NULL, **tips_tail = &tips;
5067 struct commit *commit;
5068 struct oidmap commit2todo = OIDMAP_INIT;
5069 struct string_entry *entry;
5070 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5071 shown = OIDSET_INIT;
5072 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5074 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5075 const char *cmd_pick = abbr ? "p" : "pick",
5076 *cmd_label = abbr ? "l" : "label",
5077 *cmd_reset = abbr ? "t" : "reset",
5078 *cmd_merge = abbr ? "m" : "merge";
5080 oidmap_init(&commit2todo, 0);
5081 oidmap_init(&state.commit2label, 0);
5082 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5083 strbuf_init(&state.buf, 32);
5085 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5086 struct labels_entry *onto_label_entry;
5087 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5088 FLEX_ALLOC_STR(entry, string, "onto");
5089 oidcpy(&entry->entry.oid, oid);
5090 oidmap_put(&state.commit2label, entry);
5092 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5093 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5094 hashmap_add(&state.labels, &onto_label_entry->entry);
5098 * First phase:
5099 * - get onelines for all commits
5100 * - gather all branch tips (i.e. 2nd or later parents of merges)
5101 * - label all branch tips
5103 while ((commit = get_revision(revs))) {
5104 struct commit_list *to_merge;
5105 const char *p1, *p2;
5106 struct object_id *oid;
5107 int is_empty;
5109 tail = &commit_list_insert(commit, tail)->next;
5110 oidset_insert(&interesting, &commit->object.oid);
5112 is_empty = is_original_commit_empty(commit);
5113 if (!is_empty && (commit->object.flags & PATCHSAME))
5114 continue;
5115 if (is_empty && !keep_empty)
5116 continue;
5118 strbuf_reset(&oneline);
5119 pretty_print_commit(pp, commit, &oneline);
5121 to_merge = commit->parents ? commit->parents->next : NULL;
5122 if (!to_merge) {
5123 /* non-merge commit: easy case */
5124 strbuf_reset(&buf);
5125 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5126 oid_to_hex(&commit->object.oid),
5127 oneline.buf);
5128 if (is_empty)
5129 strbuf_addf(&buf, " %c empty",
5130 comment_line_char);
5132 FLEX_ALLOC_STR(entry, string, buf.buf);
5133 oidcpy(&entry->entry.oid, &commit->object.oid);
5134 oidmap_put(&commit2todo, entry);
5136 continue;
5139 /* Create a label */
5140 strbuf_reset(&label);
5141 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5142 (p1 = strchr(p1, '\'')) &&
5143 (p2 = strchr(++p1, '\'')))
5144 strbuf_add(&label, p1, p2 - p1);
5145 else if (skip_prefix(oneline.buf, "Merge pull request ",
5146 &p1) &&
5147 (p1 = strstr(p1, " from ")))
5148 strbuf_addstr(&label, p1 + strlen(" from "));
5149 else
5150 strbuf_addbuf(&label, &oneline);
5152 strbuf_reset(&buf);
5153 strbuf_addf(&buf, "%s -C %s",
5154 cmd_merge, oid_to_hex(&commit->object.oid));
5156 /* label the tips of merged branches */
5157 for (; to_merge; to_merge = to_merge->next) {
5158 oid = &to_merge->item->object.oid;
5159 strbuf_addch(&buf, ' ');
5161 if (!oidset_contains(&interesting, oid)) {
5162 strbuf_addstr(&buf, label_oid(oid, NULL,
5163 &state));
5164 continue;
5167 tips_tail = &commit_list_insert(to_merge->item,
5168 tips_tail)->next;
5170 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5172 strbuf_addf(&buf, " # %s", oneline.buf);
5174 FLEX_ALLOC_STR(entry, string, buf.buf);
5175 oidcpy(&entry->entry.oid, &commit->object.oid);
5176 oidmap_put(&commit2todo, entry);
5180 * Second phase:
5181 * - label branch points
5182 * - add HEAD to the branch tips
5184 for (iter = commits; iter; iter = iter->next) {
5185 struct commit_list *parent = iter->item->parents;
5186 for (; parent; parent = parent->next) {
5187 struct object_id *oid = &parent->item->object.oid;
5188 if (!oidset_contains(&interesting, oid))
5189 continue;
5190 if (oidset_insert(&child_seen, oid))
5191 label_oid(oid, "branch-point", &state);
5194 /* Add HEAD as implicit "tip of branch" */
5195 if (!iter->next)
5196 tips_tail = &commit_list_insert(iter->item,
5197 tips_tail)->next;
5201 * Third phase: output the todo list. This is a bit tricky, as we
5202 * want to avoid jumping back and forth between revisions. To
5203 * accomplish that goal, we walk backwards from the branch tips,
5204 * gathering commits not yet shown, reversing the list on the fly,
5205 * then outputting that list (labeling revisions as needed).
5207 strbuf_addf(out, "%s onto\n", cmd_label);
5208 for (iter = tips; iter; iter = iter->next) {
5209 struct commit_list *list = NULL, *iter2;
5211 commit = iter->item;
5212 if (oidset_contains(&shown, &commit->object.oid))
5213 continue;
5214 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5216 if (entry)
5217 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5218 else
5219 strbuf_addch(out, '\n');
5221 while (oidset_contains(&interesting, &commit->object.oid) &&
5222 !oidset_contains(&shown, &commit->object.oid)) {
5223 commit_list_insert(commit, &list);
5224 if (!commit->parents) {
5225 commit = NULL;
5226 break;
5228 commit = commit->parents->item;
5231 if (!commit)
5232 strbuf_addf(out, "%s %s\n", cmd_reset,
5233 rebase_cousins || root_with_onto ?
5234 "onto" : "[new root]");
5235 else {
5236 const char *to = NULL;
5238 entry = oidmap_get(&state.commit2label,
5239 &commit->object.oid);
5240 if (entry)
5241 to = entry->string;
5242 else if (!rebase_cousins)
5243 to = label_oid(&commit->object.oid, NULL,
5244 &state);
5246 if (!to || !strcmp(to, "onto"))
5247 strbuf_addf(out, "%s onto\n", cmd_reset);
5248 else {
5249 strbuf_reset(&oneline);
5250 pretty_print_commit(pp, commit, &oneline);
5251 strbuf_addf(out, "%s %s # %s\n",
5252 cmd_reset, to, oneline.buf);
5256 for (iter2 = list; iter2; iter2 = iter2->next) {
5257 struct object_id *oid = &iter2->item->object.oid;
5258 entry = oidmap_get(&commit2todo, oid);
5259 /* only show if not already upstream */
5260 if (entry)
5261 strbuf_addf(out, "%s\n", entry->string);
5262 entry = oidmap_get(&state.commit2label, oid);
5263 if (entry)
5264 strbuf_addf(out, "%s %s\n",
5265 cmd_label, entry->string);
5266 oidset_insert(&shown, oid);
5269 free_commit_list(list);
5272 free_commit_list(commits);
5273 free_commit_list(tips);
5275 strbuf_release(&label);
5276 strbuf_release(&oneline);
5277 strbuf_release(&buf);
5279 oidmap_free(&commit2todo, 1);
5280 oidmap_free(&state.commit2label, 1);
5281 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5282 strbuf_release(&state.buf);
5284 return 0;
5287 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5288 const char **argv, unsigned flags)
5290 char *format = NULL;
5291 struct pretty_print_context pp = {0};
5292 struct rev_info revs;
5293 struct commit *commit;
5294 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5295 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5296 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5297 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5299 repo_init_revisions(r, &revs, NULL);
5300 revs.verbose_header = 1;
5301 if (!rebase_merges)
5302 revs.max_parents = 1;
5303 revs.cherry_mark = !reapply_cherry_picks;
5304 revs.limited = 1;
5305 revs.reverse = 1;
5306 revs.right_only = 1;
5307 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5308 revs.topo_order = 1;
5310 revs.pretty_given = 1;
5311 git_config_get_string("rebase.instructionFormat", &format);
5312 if (!format || !*format) {
5313 free(format);
5314 format = xstrdup("%s");
5316 get_commit_format(format, &revs);
5317 free(format);
5318 pp.fmt = revs.commit_format;
5319 pp.output_encoding = get_log_output_encoding();
5321 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5322 return error(_("make_script: unhandled options"));
5324 if (prepare_revision_walk(&revs) < 0)
5325 return error(_("make_script: error preparing revisions"));
5327 if (rebase_merges)
5328 return make_script_with_merges(&pp, &revs, out, flags);
5330 while ((commit = get_revision(&revs))) {
5331 int is_empty = is_original_commit_empty(commit);
5333 if (!is_empty && (commit->object.flags & PATCHSAME))
5334 continue;
5335 if (is_empty && !keep_empty)
5336 continue;
5337 strbuf_addf(out, "%s %s ", insn,
5338 oid_to_hex(&commit->object.oid));
5339 pretty_print_commit(&pp, commit, out);
5340 if (is_empty)
5341 strbuf_addf(out, " %c empty", comment_line_char);
5342 strbuf_addch(out, '\n');
5344 return 0;
5348 * Add commands after pick and (series of) squash/fixup commands
5349 * in the todo list.
5351 void todo_list_add_exec_commands(struct todo_list *todo_list,
5352 struct string_list *commands)
5354 struct strbuf *buf = &todo_list->buf;
5355 size_t base_offset = buf->len;
5356 int i, insert, nr = 0, alloc = 0;
5357 struct todo_item *items = NULL, *base_items = NULL;
5359 CALLOC_ARRAY(base_items, commands->nr);
5360 for (i = 0; i < commands->nr; i++) {
5361 size_t command_len = strlen(commands->items[i].string);
5363 strbuf_addstr(buf, commands->items[i].string);
5364 strbuf_addch(buf, '\n');
5366 base_items[i].command = TODO_EXEC;
5367 base_items[i].offset_in_buf = base_offset;
5368 base_items[i].arg_offset = base_offset + strlen("exec ");
5369 base_items[i].arg_len = command_len - strlen("exec ");
5371 base_offset += command_len + 1;
5375 * Insert <commands> after every pick. Here, fixup/squash chains
5376 * are considered part of the pick, so we insert the commands *after*
5377 * those chains if there are any.
5379 * As we insert the exec commands immediately after rearranging
5380 * any fixups and before the user edits the list, a fixup chain
5381 * can never contain comments (any comments are empty picks that
5382 * have been commented out because the user did not specify
5383 * --keep-empty). So, it is safe to insert an exec command
5384 * without looking at the command following a comment.
5386 insert = 0;
5387 for (i = 0; i < todo_list->nr; i++) {
5388 enum todo_command command = todo_list->items[i].command;
5389 if (insert && !is_fixup(command)) {
5390 ALLOC_GROW(items, nr + commands->nr, alloc);
5391 COPY_ARRAY(items + nr, base_items, commands->nr);
5392 nr += commands->nr;
5394 insert = 0;
5397 ALLOC_GROW(items, nr + 1, alloc);
5398 items[nr++] = todo_list->items[i];
5400 if (command == TODO_PICK || command == TODO_MERGE)
5401 insert = 1;
5404 /* insert or append final <commands> */
5405 if (insert || nr == todo_list->nr) {
5406 ALLOC_GROW(items, nr + commands->nr, alloc);
5407 COPY_ARRAY(items + nr, base_items, commands->nr);
5408 nr += commands->nr;
5411 free(base_items);
5412 FREE_AND_NULL(todo_list->items);
5413 todo_list->items = items;
5414 todo_list->nr = nr;
5415 todo_list->alloc = alloc;
5418 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5419 struct strbuf *buf, int num, unsigned flags)
5421 struct todo_item *item;
5422 int i, max = todo_list->nr;
5424 if (num > 0 && num < max)
5425 max = num;
5427 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5428 char cmd;
5430 /* if the item is not a command write it and continue */
5431 if (item->command >= TODO_COMMENT) {
5432 strbuf_addf(buf, "%.*s\n", item->arg_len,
5433 todo_item_get_arg(todo_list, item));
5434 continue;
5437 /* add command to the buffer */
5438 cmd = command_to_char(item->command);
5439 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5440 strbuf_addch(buf, cmd);
5441 else
5442 strbuf_addstr(buf, command_to_string(item->command));
5444 /* add commit id */
5445 if (item->commit) {
5446 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5447 short_commit_name(item->commit) :
5448 oid_to_hex(&item->commit->object.oid);
5450 if (item->command == TODO_FIXUP) {
5451 if (item->flags & TODO_EDIT_FIXUP_MSG)
5452 strbuf_addstr(buf, " -c");
5453 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5454 strbuf_addstr(buf, " -C");
5458 if (item->command == TODO_MERGE) {
5459 if (item->flags & TODO_EDIT_MERGE_MSG)
5460 strbuf_addstr(buf, " -c");
5461 else
5462 strbuf_addstr(buf, " -C");
5465 strbuf_addf(buf, " %s", oid);
5468 /* add all the rest */
5469 if (!item->arg_len)
5470 strbuf_addch(buf, '\n');
5471 else
5472 strbuf_addf(buf, " %.*s\n", item->arg_len,
5473 todo_item_get_arg(todo_list, item));
5477 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5478 const char *file, const char *shortrevisions,
5479 const char *shortonto, int num, unsigned flags)
5481 int res;
5482 struct strbuf buf = STRBUF_INIT;
5484 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5485 if (flags & TODO_LIST_APPEND_TODO_HELP)
5486 append_todo_help(count_commands(todo_list),
5487 shortrevisions, shortonto, &buf);
5489 res = write_message(buf.buf, buf.len, file, 0);
5490 strbuf_release(&buf);
5492 return res;
5495 /* skip picking commits whose parents are unchanged */
5496 static int skip_unnecessary_picks(struct repository *r,
5497 struct todo_list *todo_list,
5498 struct object_id *base_oid)
5500 struct object_id *parent_oid;
5501 int i;
5503 for (i = 0; i < todo_list->nr; i++) {
5504 struct todo_item *item = todo_list->items + i;
5506 if (item->command >= TODO_NOOP)
5507 continue;
5508 if (item->command != TODO_PICK)
5509 break;
5510 if (parse_commit(item->commit)) {
5511 return error(_("could not parse commit '%s'"),
5512 oid_to_hex(&item->commit->object.oid));
5514 if (!item->commit->parents)
5515 break; /* root commit */
5516 if (item->commit->parents->next)
5517 break; /* merge commit */
5518 parent_oid = &item->commit->parents->item->object.oid;
5519 if (!oideq(parent_oid, base_oid))
5520 break;
5521 oidcpy(base_oid, &item->commit->object.oid);
5523 if (i > 0) {
5524 const char *done_path = rebase_path_done();
5526 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5527 error_errno(_("could not write to '%s'"), done_path);
5528 return -1;
5531 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5532 todo_list->nr -= i;
5533 todo_list->current = 0;
5534 todo_list->done_nr += i;
5536 if (is_fixup(peek_command(todo_list, 0)))
5537 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5540 return 0;
5543 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5544 const char *shortrevisions, const char *onto_name,
5545 struct commit *onto, const struct object_id *orig_head,
5546 struct string_list *commands, unsigned autosquash,
5547 struct todo_list *todo_list)
5549 char shortonto[GIT_MAX_HEXSZ + 1];
5550 const char *todo_file = rebase_path_todo();
5551 struct todo_list new_todo = TODO_LIST_INIT;
5552 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5553 struct object_id oid = onto->object.oid;
5554 int res;
5556 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5558 if (buf->len == 0) {
5559 struct todo_item *item = append_new_todo(todo_list);
5560 item->command = TODO_NOOP;
5561 item->commit = NULL;
5562 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5565 if (autosquash && todo_list_rearrange_squash(todo_list))
5566 return -1;
5568 if (commands->nr)
5569 todo_list_add_exec_commands(todo_list, commands);
5571 if (count_commands(todo_list) == 0) {
5572 apply_autostash(rebase_path_autostash());
5573 sequencer_remove_state(opts);
5575 return error(_("nothing to do"));
5578 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5579 shortonto, flags);
5580 if (res == -1)
5581 return -1;
5582 else if (res == -2) {
5583 apply_autostash(rebase_path_autostash());
5584 sequencer_remove_state(opts);
5586 return -1;
5587 } else if (res == -3) {
5588 apply_autostash(rebase_path_autostash());
5589 sequencer_remove_state(opts);
5590 todo_list_release(&new_todo);
5592 return error(_("nothing to do"));
5593 } else if (res == -4) {
5594 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5595 todo_list_release(&new_todo);
5597 return -1;
5600 /* Expand the commit IDs */
5601 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5602 strbuf_swap(&new_todo.buf, &buf2);
5603 strbuf_release(&buf2);
5604 new_todo.total_nr -= new_todo.nr;
5605 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5606 BUG("invalid todo list after expanding IDs:\n%s",
5607 new_todo.buf.buf);
5609 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5610 todo_list_release(&new_todo);
5611 return error(_("could not skip unnecessary pick commands"));
5614 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5615 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5616 todo_list_release(&new_todo);
5617 return error_errno(_("could not write '%s'"), todo_file);
5620 res = -1;
5622 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5623 goto cleanup;
5625 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5626 goto cleanup;
5628 todo_list_write_total_nr(&new_todo);
5629 res = pick_commits(r, &new_todo, opts);
5631 cleanup:
5632 todo_list_release(&new_todo);
5634 return res;
5637 struct subject2item_entry {
5638 struct hashmap_entry entry;
5639 int i;
5640 char subject[FLEX_ARRAY];
5643 static int subject2item_cmp(const void *fndata,
5644 const struct hashmap_entry *eptr,
5645 const struct hashmap_entry *entry_or_key,
5646 const void *key)
5648 const struct subject2item_entry *a, *b;
5650 a = container_of(eptr, const struct subject2item_entry, entry);
5651 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5653 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5656 define_commit_slab(commit_todo_item, struct todo_item *);
5658 static int skip_fixupish(const char *subject, const char **p) {
5659 return skip_prefix(subject, "fixup! ", p) ||
5660 skip_prefix(subject, "amend! ", p) ||
5661 skip_prefix(subject, "squash! ", p);
5665 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5666 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5667 * after the former, and change "pick" to "fixup"/"squash".
5669 * Note that if the config has specified a custom instruction format, each log
5670 * message will have to be retrieved from the commit (as the oneline in the
5671 * script cannot be trusted) in order to normalize the autosquash arrangement.
5673 int todo_list_rearrange_squash(struct todo_list *todo_list)
5675 struct hashmap subject2item;
5676 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5677 char **subjects;
5678 struct commit_todo_item commit_todo;
5679 struct todo_item *items = NULL;
5681 init_commit_todo_item(&commit_todo);
5683 * The hashmap maps onelines to the respective todo list index.
5685 * If any items need to be rearranged, the next[i] value will indicate
5686 * which item was moved directly after the i'th.
5688 * In that case, last[i] will indicate the index of the latest item to
5689 * be moved to appear after the i'th.
5691 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5692 ALLOC_ARRAY(next, todo_list->nr);
5693 ALLOC_ARRAY(tail, todo_list->nr);
5694 ALLOC_ARRAY(subjects, todo_list->nr);
5695 for (i = 0; i < todo_list->nr; i++) {
5696 struct strbuf buf = STRBUF_INIT;
5697 struct todo_item *item = todo_list->items + i;
5698 const char *commit_buffer, *subject, *p;
5699 size_t subject_len;
5700 int i2 = -1;
5701 struct subject2item_entry *entry;
5703 next[i] = tail[i] = -1;
5704 if (!item->commit || item->command == TODO_DROP) {
5705 subjects[i] = NULL;
5706 continue;
5709 if (is_fixup(item->command)) {
5710 clear_commit_todo_item(&commit_todo);
5711 return error(_("the script was already rearranged."));
5714 *commit_todo_item_at(&commit_todo, item->commit) = item;
5716 parse_commit(item->commit);
5717 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5718 find_commit_subject(commit_buffer, &subject);
5719 format_subject(&buf, subject, " ");
5720 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5721 unuse_commit_buffer(item->commit, commit_buffer);
5722 if (skip_fixupish(subject, &p)) {
5723 struct commit *commit2;
5725 for (;;) {
5726 while (isspace(*p))
5727 p++;
5728 if (!skip_fixupish(p, &p))
5729 break;
5732 entry = hashmap_get_entry_from_hash(&subject2item,
5733 strhash(p), p,
5734 struct subject2item_entry,
5735 entry);
5736 if (entry)
5737 /* found by title */
5738 i2 = entry->i;
5739 else if (!strchr(p, ' ') &&
5740 (commit2 =
5741 lookup_commit_reference_by_name(p)) &&
5742 *commit_todo_item_at(&commit_todo, commit2))
5743 /* found by commit name */
5744 i2 = *commit_todo_item_at(&commit_todo, commit2)
5745 - todo_list->items;
5746 else {
5747 /* copy can be a prefix of the commit subject */
5748 for (i2 = 0; i2 < i; i2++)
5749 if (subjects[i2] &&
5750 starts_with(subjects[i2], p))
5751 break;
5752 if (i2 == i)
5753 i2 = -1;
5756 if (i2 >= 0) {
5757 rearranged = 1;
5758 if (starts_with(subject, "fixup!")) {
5759 todo_list->items[i].command = TODO_FIXUP;
5760 } else if (starts_with(subject, "amend!")) {
5761 todo_list->items[i].command = TODO_FIXUP;
5762 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5763 } else {
5764 todo_list->items[i].command = TODO_SQUASH;
5766 if (tail[i2] < 0) {
5767 next[i] = next[i2];
5768 next[i2] = i;
5769 } else {
5770 next[i] = next[tail[i2]];
5771 next[tail[i2]] = i;
5773 tail[i2] = i;
5774 } else if (!hashmap_get_from_hash(&subject2item,
5775 strhash(subject), subject)) {
5776 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5777 entry->i = i;
5778 hashmap_entry_init(&entry->entry,
5779 strhash(entry->subject));
5780 hashmap_put(&subject2item, &entry->entry);
5784 if (rearranged) {
5785 for (i = 0; i < todo_list->nr; i++) {
5786 enum todo_command command = todo_list->items[i].command;
5787 int cur = i;
5790 * Initially, all commands are 'pick's. If it is a
5791 * fixup or a squash now, we have rearranged it.
5793 if (is_fixup(command))
5794 continue;
5796 while (cur >= 0) {
5797 ALLOC_GROW(items, nr + 1, alloc);
5798 items[nr++] = todo_list->items[cur];
5799 cur = next[cur];
5803 FREE_AND_NULL(todo_list->items);
5804 todo_list->items = items;
5805 todo_list->nr = nr;
5806 todo_list->alloc = alloc;
5809 free(next);
5810 free(tail);
5811 for (i = 0; i < todo_list->nr; i++)
5812 free(subjects[i]);
5813 free(subjects);
5814 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5816 clear_commit_todo_item(&commit_todo);
5818 return 0;
5821 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5823 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5824 struct object_id cherry_pick_head, rebase_head;
5826 if (file_exists(git_path_seq_dir()))
5827 *whence = FROM_CHERRY_PICK_MULTI;
5828 if (file_exists(rebase_path()) &&
5829 !get_oid("REBASE_HEAD", &rebase_head) &&
5830 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5831 oideq(&rebase_head, &cherry_pick_head))
5832 *whence = FROM_REBASE_PICK;
5833 else
5834 *whence = FROM_CHERRY_PICK_SINGLE;
5836 return 1;
5839 return 0;