completion: improve handling of --detach in checkout
[git/raj.git] / sequencer.c
blobf30bb73c703a2b872dec85de7c68f6aa6c0b075d
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-recursive.h"
18 #include "refs.h"
19 #include "argv-array.h"
20 #include "quote.h"
21 #include "trailer.h"
22 #include "log-tree.h"
23 #include "wt-status.h"
24 #include "hashmap.h"
25 #include "notes-utils.h"
26 #include "sigchain.h"
27 #include "unpack-trees.h"
28 #include "worktree.h"
29 #include "oidmap.h"
30 #include "oidset.h"
31 #include "commit-slab.h"
32 #include "alias.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
60 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
63 * The rebase command lines that have already been processed. A line
64 * is moved here when it is first handled, before any associated user
65 * actions.
67 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
69 * The file to keep track of how many commands were already processed (e.g.
70 * for the prompt).
72 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
74 * The file to keep track of how many commands are to be processed in total
75 * (e.g. for the prompt).
77 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
79 * The commit message that is planned to be used for any changes that
80 * need to be committed following a user interaction.
82 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
84 * The file into which is accumulated the suggested commit message for
85 * squash/fixup commands. When the first of a series of squash/fixups
86 * is seen, the file is created and the commit message from the
87 * previous commit and from the first squash/fixup commit are written
88 * to it. The commit message for each subsequent squash/fixup commit
89 * is appended to the file as it is processed.
91 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
93 * If the current series of squash/fixups has not yet included a squash
94 * command, then this file exists and holds the commit message of the
95 * original "pick" commit. (If the series ends without a "squash"
96 * command, then this can be used as the commit message of the combined
97 * commit without opening the editor.)
99 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
101 * This file contains the list fixup/squash commands that have been
102 * accumulated into message-fixup or message-squash so far.
104 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
106 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
107 * GIT_AUTHOR_DATE that will be used for the commit that is currently
108 * being rebased.
110 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
112 * When an "edit" rebase command is being processed, the SHA1 of the
113 * commit to be edited is recorded in this file. When "git rebase
114 * --continue" is executed, if there are any staged changes then they
115 * will be amended to the HEAD commit, but only provided the HEAD
116 * commit is still the commit to be edited. When any other rebase
117 * command is processed, this file is deleted.
119 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
121 * When we stop at a given patch via the "edit" command, this file contains
122 * the abbreviated commit name of the corresponding patch.
124 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
126 * For the post-rewrite hook, we make a list of rewritten commits and
127 * their new sha1s. The rewritten-pending list keeps the sha1s of
128 * commits that have been processed, but not committed yet,
129 * e.g. because they are waiting for a 'squash' command.
131 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
132 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
133 "rebase-merge/rewritten-pending")
136 * The path of the file containing the OID of the "squash onto" commit, i.e.
137 * the dummy commit used for `reset [new root]`.
139 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
142 * The path of the file listing refs that need to be deleted after the rebase
143 * finishes. This is used by the `label` command to record the need for cleanup.
145 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
148 * The following files are written by git-rebase just after parsing the
149 * command-line.
151 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
152 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
153 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
154 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
155 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
156 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
157 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
158 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
159 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
160 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
161 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
162 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
163 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
164 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
166 static int git_sequencer_config(const char *k, const char *v, void *cb)
168 struct replay_opts *opts = cb;
169 int status;
171 if (!strcmp(k, "commit.cleanup")) {
172 const char *s;
174 status = git_config_string(&s, k, v);
175 if (status)
176 return status;
178 if (!strcmp(s, "verbatim")) {
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "whitespace")) {
182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "strip")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "scissors")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
189 opts->explicit_cleanup = 1;
190 } else {
191 warning(_("invalid commit message cleanup mode '%s'"),
195 free((char *)s);
196 return status;
199 if (!strcmp(k, "commit.gpgsign")) {
200 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
201 return 0;
204 status = git_gpg_config(k, v, NULL);
205 if (status)
206 return status;
208 return git_diff_basic_config(k, v, NULL);
211 void sequencer_init_config(struct replay_opts *opts)
213 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
214 git_config(git_sequencer_config, opts);
217 static inline int is_rebase_i(const struct replay_opts *opts)
219 return opts->action == REPLAY_INTERACTIVE_REBASE;
222 static const char *get_dir(const struct replay_opts *opts)
224 if (is_rebase_i(opts))
225 return rebase_path();
226 return git_path_seq_dir();
229 static const char *get_todo_path(const struct replay_opts *opts)
231 if (is_rebase_i(opts))
232 return rebase_path_todo();
233 return git_path_todo_file();
237 * Returns 0 for non-conforming footer
238 * Returns 1 for conforming footer
239 * Returns 2 when sob exists within conforming footer
240 * Returns 3 when sob exists within conforming footer as last entry
242 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
243 size_t ignore_footer)
245 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
246 struct trailer_info info;
247 size_t i;
248 int found_sob = 0, found_sob_last = 0;
250 opts.no_divider = 1;
252 trailer_info_get(&info, sb->buf, &opts);
254 if (info.trailer_start == info.trailer_end)
255 return 0;
257 for (i = 0; i < info.trailer_nr; i++)
258 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
259 found_sob = 1;
260 if (i == info.trailer_nr - 1)
261 found_sob_last = 1;
264 trailer_info_release(&info);
266 if (found_sob_last)
267 return 3;
268 if (found_sob)
269 return 2;
270 return 1;
273 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
275 static struct strbuf buf = STRBUF_INIT;
277 strbuf_reset(&buf);
278 if (opts->gpg_sign)
279 sq_quotef(&buf, "-S%s", opts->gpg_sign);
280 return buf.buf;
283 int sequencer_remove_state(struct replay_opts *opts)
285 struct strbuf buf = STRBUF_INIT;
286 int i, ret = 0;
288 if (is_rebase_i(opts) &&
289 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
290 char *p = buf.buf;
291 while (*p) {
292 char *eol = strchr(p, '\n');
293 if (eol)
294 *eol = '\0';
295 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
296 warning(_("could not delete '%s'"), p);
297 ret = -1;
299 if (!eol)
300 break;
301 p = eol + 1;
305 free(opts->gpg_sign);
306 free(opts->strategy);
307 for (i = 0; i < opts->xopts_nr; i++)
308 free(opts->xopts[i]);
309 free(opts->xopts);
310 strbuf_release(&opts->current_fixups);
312 strbuf_reset(&buf);
313 strbuf_addstr(&buf, get_dir(opts));
314 if (remove_dir_recursively(&buf, 0))
315 ret = error(_("could not remove '%s'"), buf.buf);
316 strbuf_release(&buf);
318 return ret;
321 static const char *action_name(const struct replay_opts *opts)
323 switch (opts->action) {
324 case REPLAY_REVERT:
325 return N_("revert");
326 case REPLAY_PICK:
327 return N_("cherry-pick");
328 case REPLAY_INTERACTIVE_REBASE:
329 return N_("rebase");
331 die(_("unknown action: %d"), opts->action);
334 struct commit_message {
335 char *parent_label;
336 char *label;
337 char *subject;
338 const char *message;
341 static const char *short_commit_name(struct commit *commit)
343 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
346 static int get_message(struct commit *commit, struct commit_message *out)
348 const char *abbrev, *subject;
349 int subject_len;
351 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
352 abbrev = short_commit_name(commit);
354 subject_len = find_commit_subject(out->message, &subject);
356 out->subject = xmemdupz(subject, subject_len);
357 out->label = xstrfmt("%s... %s", abbrev, out->subject);
358 out->parent_label = xstrfmt("parent of %s", out->label);
360 return 0;
363 static void free_message(struct commit *commit, struct commit_message *msg)
365 free(msg->parent_label);
366 free(msg->label);
367 free(msg->subject);
368 unuse_commit_buffer(commit, msg->message);
371 static void print_advice(struct repository *r, int show_hint,
372 struct replay_opts *opts)
374 char *msg = getenv("GIT_CHERRY_PICK_HELP");
376 if (msg) {
377 fprintf(stderr, "%s\n", msg);
379 * A conflict has occurred but the porcelain
380 * (typically rebase --interactive) wants to take care
381 * of the commit itself so remove CHERRY_PICK_HEAD
383 unlink(git_path_cherry_pick_head(r));
384 return;
387 if (show_hint) {
388 if (opts->no_commit)
389 advise(_("after resolving the conflicts, mark the corrected paths\n"
390 "with 'git add <paths>' or 'git rm <paths>'"));
391 else
392 advise(_("after resolving the conflicts, mark the corrected paths\n"
393 "with 'git add <paths>' or 'git rm <paths>'\n"
394 "and commit the result with 'git commit'"));
398 static int write_message(const void *buf, size_t len, const char *filename,
399 int append_eol)
401 struct lock_file msg_file = LOCK_INIT;
403 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
404 if (msg_fd < 0)
405 return error_errno(_("could not lock '%s'"), filename);
406 if (write_in_full(msg_fd, buf, len) < 0) {
407 error_errno(_("could not write to '%s'"), filename);
408 rollback_lock_file(&msg_file);
409 return -1;
411 if (append_eol && write(msg_fd, "\n", 1) < 0) {
412 error_errno(_("could not write eol to '%s'"), filename);
413 rollback_lock_file(&msg_file);
414 return -1;
416 if (commit_lock_file(&msg_file) < 0)
417 return error(_("failed to finalize '%s'"), filename);
419 return 0;
423 * Reads a file that was presumably written by a shell script, i.e. with an
424 * end-of-line marker that needs to be stripped.
426 * Note that only the last end-of-line marker is stripped, consistent with the
427 * behavior of "$(cat path)" in a shell script.
429 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
431 static int read_oneliner(struct strbuf *buf,
432 const char *path, int skip_if_empty)
434 int orig_len = buf->len;
436 if (!file_exists(path))
437 return 0;
439 if (strbuf_read_file(buf, path, 0) < 0) {
440 warning_errno(_("could not read '%s'"), path);
441 return 0;
444 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
445 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
446 --buf->len;
447 buf->buf[buf->len] = '\0';
450 if (skip_if_empty && buf->len == orig_len)
451 return 0;
453 return 1;
456 static struct tree *empty_tree(struct repository *r)
458 return lookup_tree(r, the_hash_algo->empty_tree);
461 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
463 if (repo_read_index_unmerged(repo))
464 return error_resolve_conflict(_(action_name(opts)));
466 error(_("your local changes would be overwritten by %s."),
467 _(action_name(opts)));
469 if (advice_commit_before_merge)
470 advise(_("commit your changes or stash them to proceed."));
471 return -1;
474 static void update_abort_safety_file(void)
476 struct object_id head;
478 /* Do nothing on a single-pick */
479 if (!file_exists(git_path_seq_dir()))
480 return;
482 if (!get_oid("HEAD", &head))
483 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
484 else
485 write_file(git_path_abort_safety_file(), "%s", "");
488 static int fast_forward_to(struct repository *r,
489 const struct object_id *to,
490 const struct object_id *from,
491 int unborn,
492 struct replay_opts *opts)
494 struct ref_transaction *transaction;
495 struct strbuf sb = STRBUF_INIT;
496 struct strbuf err = STRBUF_INIT;
498 repo_read_index(r);
499 if (checkout_fast_forward(r, from, to, 1))
500 return -1; /* the callee should have complained already */
502 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
504 transaction = ref_transaction_begin(&err);
505 if (!transaction ||
506 ref_transaction_update(transaction, "HEAD",
507 to, unborn && !is_rebase_i(opts) ?
508 &null_oid : from,
509 0, sb.buf, &err) ||
510 ref_transaction_commit(transaction, &err)) {
511 ref_transaction_free(transaction);
512 error("%s", err.buf);
513 strbuf_release(&sb);
514 strbuf_release(&err);
515 return -1;
518 strbuf_release(&sb);
519 strbuf_release(&err);
520 ref_transaction_free(transaction);
521 update_abort_safety_file();
522 return 0;
525 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
526 int use_editor)
528 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
529 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
530 COMMIT_MSG_CLEANUP_SPACE;
531 else if (!strcmp(cleanup_arg, "verbatim"))
532 return COMMIT_MSG_CLEANUP_NONE;
533 else if (!strcmp(cleanup_arg, "whitespace"))
534 return COMMIT_MSG_CLEANUP_SPACE;
535 else if (!strcmp(cleanup_arg, "strip"))
536 return COMMIT_MSG_CLEANUP_ALL;
537 else if (!strcmp(cleanup_arg, "scissors"))
538 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
539 COMMIT_MSG_CLEANUP_SPACE;
540 else
541 die(_("Invalid cleanup mode %s"), cleanup_arg);
545 * NB using int rather than enum cleanup_mode to stop clang's
546 * -Wtautological-constant-out-of-range-compare complaining that the comparison
547 * is always true.
549 static const char *describe_cleanup_mode(int cleanup_mode)
551 static const char *modes[] = { "whitespace",
552 "verbatim",
553 "scissors",
554 "strip" };
556 if (cleanup_mode < ARRAY_SIZE(modes))
557 return modes[cleanup_mode];
559 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
562 void append_conflicts_hint(struct index_state *istate,
563 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
565 int i;
567 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
568 strbuf_addch(msgbuf, '\n');
569 wt_status_append_cut_line(msgbuf);
570 strbuf_addch(msgbuf, comment_line_char);
573 strbuf_addch(msgbuf, '\n');
574 strbuf_commented_addf(msgbuf, "Conflicts:\n");
575 for (i = 0; i < istate->cache_nr;) {
576 const struct cache_entry *ce = istate->cache[i++];
577 if (ce_stage(ce)) {
578 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
579 while (i < istate->cache_nr &&
580 !strcmp(ce->name, istate->cache[i]->name))
581 i++;
586 static int do_recursive_merge(struct repository *r,
587 struct commit *base, struct commit *next,
588 const char *base_label, const char *next_label,
589 struct object_id *head, struct strbuf *msgbuf,
590 struct replay_opts *opts)
592 struct merge_options o;
593 struct tree *next_tree, *base_tree, *head_tree;
594 int clean;
595 int i;
596 struct lock_file index_lock = LOCK_INIT;
598 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
599 return -1;
601 repo_read_index(r);
603 init_merge_options(&o, r);
604 o.ancestor = base ? base_label : "(empty tree)";
605 o.branch1 = "HEAD";
606 o.branch2 = next ? next_label : "(empty tree)";
607 if (is_rebase_i(opts))
608 o.buffer_output = 2;
609 o.show_rename_progress = 1;
611 head_tree = parse_tree_indirect(head);
612 next_tree = next ? get_commit_tree(next) : empty_tree(r);
613 base_tree = base ? get_commit_tree(base) : empty_tree(r);
615 for (i = 0; i < opts->xopts_nr; i++)
616 parse_merge_opt(&o, opts->xopts[i]);
618 clean = merge_trees(&o,
619 head_tree,
620 next_tree, base_tree);
621 if (is_rebase_i(opts) && clean <= 0)
622 fputs(o.obuf.buf, stdout);
623 strbuf_release(&o.obuf);
624 if (clean < 0) {
625 rollback_lock_file(&index_lock);
626 return clean;
629 if (write_locked_index(r->index, &index_lock,
630 COMMIT_LOCK | SKIP_IF_UNCHANGED))
632 * TRANSLATORS: %s will be "revert", "cherry-pick" or
633 * "rebase".
635 return error(_("%s: Unable to write new index file"),
636 _(action_name(opts)));
638 if (!clean)
639 append_conflicts_hint(r->index, msgbuf,
640 opts->default_msg_cleanup);
642 return !clean;
645 static struct object_id *get_cache_tree_oid(struct index_state *istate)
647 if (!istate->cache_tree)
648 istate->cache_tree = cache_tree();
650 if (!cache_tree_fully_valid(istate->cache_tree))
651 if (cache_tree_update(istate, 0)) {
652 error(_("unable to update cache tree"));
653 return NULL;
656 return &istate->cache_tree->oid;
659 static int is_index_unchanged(struct repository *r)
661 struct object_id head_oid, *cache_tree_oid;
662 struct commit *head_commit;
663 struct index_state *istate = r->index;
665 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
666 return error(_("could not resolve HEAD commit"));
668 head_commit = lookup_commit(r, &head_oid);
671 * If head_commit is NULL, check_commit, called from
672 * lookup_commit, would have indicated that head_commit is not
673 * a commit object already. parse_commit() will return failure
674 * without further complaints in such a case. Otherwise, if
675 * the commit is invalid, parse_commit() will complain. So
676 * there is nothing for us to say here. Just return failure.
678 if (parse_commit(head_commit))
679 return -1;
681 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
682 return -1;
684 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
687 static int write_author_script(const char *message)
689 struct strbuf buf = STRBUF_INIT;
690 const char *eol;
691 int res;
693 for (;;)
694 if (!*message || starts_with(message, "\n")) {
695 missing_author:
696 /* Missing 'author' line? */
697 unlink(rebase_path_author_script());
698 return 0;
699 } else if (skip_prefix(message, "author ", &message))
700 break;
701 else if ((eol = strchr(message, '\n')))
702 message = eol + 1;
703 else
704 goto missing_author;
706 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
707 while (*message && *message != '\n' && *message != '\r')
708 if (skip_prefix(message, " <", &message))
709 break;
710 else if (*message != '\'')
711 strbuf_addch(&buf, *(message++));
712 else
713 strbuf_addf(&buf, "'\\%c'", *(message++));
714 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
715 while (*message && *message != '\n' && *message != '\r')
716 if (skip_prefix(message, "> ", &message))
717 break;
718 else if (*message != '\'')
719 strbuf_addch(&buf, *(message++));
720 else
721 strbuf_addf(&buf, "'\\%c'", *(message++));
722 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
723 while (*message && *message != '\n' && *message != '\r')
724 if (*message != '\'')
725 strbuf_addch(&buf, *(message++));
726 else
727 strbuf_addf(&buf, "'\\%c'", *(message++));
728 strbuf_addch(&buf, '\'');
729 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
730 strbuf_release(&buf);
731 return res;
735 * Take a series of KEY='VALUE' lines where VALUE part is
736 * sq-quoted, and append <KEY, VALUE> at the end of the string list
738 static int parse_key_value_squoted(char *buf, struct string_list *list)
740 while (*buf) {
741 struct string_list_item *item;
742 char *np;
743 char *cp = strchr(buf, '=');
744 if (!cp) {
745 np = strchrnul(buf, '\n');
746 return error(_("no key present in '%.*s'"),
747 (int) (np - buf), buf);
749 np = strchrnul(cp, '\n');
750 *cp++ = '\0';
751 item = string_list_append(list, buf);
753 buf = np + (*np == '\n');
754 *np = '\0';
755 cp = sq_dequote(cp);
756 if (!cp)
757 return error(_("unable to dequote value of '%s'"),
758 item->string);
759 item->util = xstrdup(cp);
761 return 0;
765 * Reads and parses the state directory's "author-script" file, and sets name,
766 * email and date accordingly.
767 * Returns 0 on success, -1 if the file could not be parsed.
769 * The author script is of the format:
771 * GIT_AUTHOR_NAME='$author_name'
772 * GIT_AUTHOR_EMAIL='$author_email'
773 * GIT_AUTHOR_DATE='$author_date'
775 * where $author_name, $author_email and $author_date are quoted. We are strict
776 * with our parsing, as the file was meant to be eval'd in the now-removed
777 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
778 * from what this function expects, it is better to bail out than to do
779 * something that the user does not expect.
781 int read_author_script(const char *path, char **name, char **email, char **date,
782 int allow_missing)
784 struct strbuf buf = STRBUF_INIT;
785 struct string_list kv = STRING_LIST_INIT_DUP;
786 int retval = -1; /* assume failure */
787 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
789 if (strbuf_read_file(&buf, path, 256) <= 0) {
790 strbuf_release(&buf);
791 if (errno == ENOENT && allow_missing)
792 return 0;
793 else
794 return error_errno(_("could not open '%s' for reading"),
795 path);
798 if (parse_key_value_squoted(buf.buf, &kv))
799 goto finish;
801 for (i = 0; i < kv.nr; i++) {
802 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
803 if (name_i != -2)
804 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
805 else
806 name_i = i;
807 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
808 if (email_i != -2)
809 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
810 else
811 email_i = i;
812 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
813 if (date_i != -2)
814 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
815 else
816 date_i = i;
817 } else {
818 err = error(_("unknown variable '%s'"),
819 kv.items[i].string);
822 if (name_i == -2)
823 error(_("missing 'GIT_AUTHOR_NAME'"));
824 if (email_i == -2)
825 error(_("missing 'GIT_AUTHOR_EMAIL'"));
826 if (date_i == -2)
827 error(_("missing 'GIT_AUTHOR_DATE'"));
828 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
829 goto finish;
830 *name = kv.items[name_i].util;
831 *email = kv.items[email_i].util;
832 *date = kv.items[date_i].util;
833 retval = 0;
834 finish:
835 string_list_clear(&kv, !!retval);
836 strbuf_release(&buf);
837 return retval;
841 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
842 * file with shell quoting into struct argv_array. Returns -1 on
843 * error, 0 otherwise.
845 static int read_env_script(struct argv_array *env)
847 char *name, *email, *date;
849 if (read_author_script(rebase_path_author_script(),
850 &name, &email, &date, 0))
851 return -1;
853 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
854 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
855 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
856 free(name);
857 free(email);
858 free(date);
860 return 0;
863 static char *get_author(const char *message)
865 size_t len;
866 const char *a;
868 a = find_commit_header(message, "author", &len);
869 if (a)
870 return xmemdupz(a, len);
872 return NULL;
875 static const char staged_changes_advice[] =
876 N_("you have staged changes in your working tree\n"
877 "If these changes are meant to be squashed into the previous commit, run:\n"
878 "\n"
879 " git commit --amend %s\n"
880 "\n"
881 "If they are meant to go into a new commit, run:\n"
882 "\n"
883 " git commit %s\n"
884 "\n"
885 "In both cases, once you're done, continue with:\n"
886 "\n"
887 " git rebase --continue\n");
889 #define ALLOW_EMPTY (1<<0)
890 #define EDIT_MSG (1<<1)
891 #define AMEND_MSG (1<<2)
892 #define CLEANUP_MSG (1<<3)
893 #define VERIFY_MSG (1<<4)
894 #define CREATE_ROOT_COMMIT (1<<5)
896 static int run_command_silent_on_success(struct child_process *cmd)
898 struct strbuf buf = STRBUF_INIT;
899 int rc;
901 cmd->stdout_to_stderr = 1;
902 rc = pipe_command(cmd,
903 NULL, 0,
904 NULL, 0,
905 &buf, 0);
907 if (rc)
908 fputs(buf.buf, stderr);
909 strbuf_release(&buf);
910 return rc;
914 * If we are cherry-pick, and if the merge did not result in
915 * hand-editing, we will hit this commit and inherit the original
916 * author date and name.
918 * If we are revert, or if our cherry-pick results in a hand merge,
919 * we had better say that the current user is responsible for that.
921 * An exception is when run_git_commit() is called during an
922 * interactive rebase: in that case, we will want to retain the
923 * author metadata.
925 static int run_git_commit(struct repository *r,
926 const char *defmsg,
927 struct replay_opts *opts,
928 unsigned int flags)
930 struct child_process cmd = CHILD_PROCESS_INIT;
932 cmd.git_cmd = 1;
934 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
935 const char *gpg_opt = gpg_sign_opt_quoted(opts);
937 return error(_(staged_changes_advice),
938 gpg_opt, gpg_opt);
941 argv_array_push(&cmd.args, "commit");
943 if (!(flags & VERIFY_MSG))
944 argv_array_push(&cmd.args, "-n");
945 if ((flags & AMEND_MSG))
946 argv_array_push(&cmd.args, "--amend");
947 if (opts->gpg_sign)
948 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
949 else
950 argv_array_push(&cmd.args, "--no-gpg-sign");
951 if (defmsg)
952 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
953 else if (!(flags & EDIT_MSG))
954 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
955 if ((flags & CLEANUP_MSG))
956 argv_array_push(&cmd.args, "--cleanup=strip");
957 if ((flags & EDIT_MSG))
958 argv_array_push(&cmd.args, "-e");
959 else if (!(flags & CLEANUP_MSG) &&
960 !opts->signoff && !opts->record_origin &&
961 !opts->explicit_cleanup)
962 argv_array_push(&cmd.args, "--cleanup=verbatim");
964 if ((flags & ALLOW_EMPTY))
965 argv_array_push(&cmd.args, "--allow-empty");
967 if (!(flags & EDIT_MSG))
968 argv_array_push(&cmd.args, "--allow-empty-message");
970 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
971 return run_command_silent_on_success(&cmd);
972 else
973 return run_command(&cmd);
976 static int rest_is_empty(const struct strbuf *sb, int start)
978 int i, eol;
979 const char *nl;
981 /* Check if the rest is just whitespace and Signed-off-by's. */
982 for (i = start; i < sb->len; i++) {
983 nl = memchr(sb->buf + i, '\n', sb->len - i);
984 if (nl)
985 eol = nl - sb->buf;
986 else
987 eol = sb->len;
989 if (strlen(sign_off_header) <= eol - i &&
990 starts_with(sb->buf + i, sign_off_header)) {
991 i = eol;
992 continue;
994 while (i < eol)
995 if (!isspace(sb->buf[i++]))
996 return 0;
999 return 1;
1002 void cleanup_message(struct strbuf *msgbuf,
1003 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1005 if (verbose || /* Truncate the message just before the diff, if any. */
1006 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1007 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1008 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1009 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1013 * Find out if the message in the strbuf contains only whitespace and
1014 * Signed-off-by lines.
1016 int message_is_empty(const struct strbuf *sb,
1017 enum commit_msg_cleanup_mode cleanup_mode)
1019 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1020 return 0;
1021 return rest_is_empty(sb, 0);
1025 * See if the user edited the message in the editor or left what
1026 * was in the template intact
1028 int template_untouched(const struct strbuf *sb, const char *template_file,
1029 enum commit_msg_cleanup_mode cleanup_mode)
1031 struct strbuf tmpl = STRBUF_INIT;
1032 const char *start;
1034 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1035 return 0;
1037 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1038 return 0;
1040 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1041 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1042 start = sb->buf;
1043 strbuf_release(&tmpl);
1044 return rest_is_empty(sb, start - sb->buf);
1047 int update_head_with_reflog(const struct commit *old_head,
1048 const struct object_id *new_head,
1049 const char *action, const struct strbuf *msg,
1050 struct strbuf *err)
1052 struct ref_transaction *transaction;
1053 struct strbuf sb = STRBUF_INIT;
1054 const char *nl;
1055 int ret = 0;
1057 if (action) {
1058 strbuf_addstr(&sb, action);
1059 strbuf_addstr(&sb, ": ");
1062 nl = strchr(msg->buf, '\n');
1063 if (nl) {
1064 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1065 } else {
1066 strbuf_addbuf(&sb, msg);
1067 strbuf_addch(&sb, '\n');
1070 transaction = ref_transaction_begin(err);
1071 if (!transaction ||
1072 ref_transaction_update(transaction, "HEAD", new_head,
1073 old_head ? &old_head->object.oid : &null_oid,
1074 0, sb.buf, err) ||
1075 ref_transaction_commit(transaction, err)) {
1076 ret = -1;
1078 ref_transaction_free(transaction);
1079 strbuf_release(&sb);
1081 return ret;
1084 static int run_rewrite_hook(const struct object_id *oldoid,
1085 const struct object_id *newoid)
1087 struct child_process proc = CHILD_PROCESS_INIT;
1088 const char *argv[3];
1089 int code;
1090 struct strbuf sb = STRBUF_INIT;
1092 argv[0] = find_hook("post-rewrite");
1093 if (!argv[0])
1094 return 0;
1096 argv[1] = "amend";
1097 argv[2] = NULL;
1099 proc.argv = argv;
1100 proc.in = -1;
1101 proc.stdout_to_stderr = 1;
1102 proc.trace2_hook_name = "post-rewrite";
1104 code = start_command(&proc);
1105 if (code)
1106 return code;
1107 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1108 sigchain_push(SIGPIPE, SIG_IGN);
1109 write_in_full(proc.in, sb.buf, sb.len);
1110 close(proc.in);
1111 strbuf_release(&sb);
1112 sigchain_pop(SIGPIPE);
1113 return finish_command(&proc);
1116 void commit_post_rewrite(struct repository *r,
1117 const struct commit *old_head,
1118 const struct object_id *new_head)
1120 struct notes_rewrite_cfg *cfg;
1122 cfg = init_copy_notes_for_rewrite("amend");
1123 if (cfg) {
1124 /* we are amending, so old_head is not NULL */
1125 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1126 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1128 run_rewrite_hook(&old_head->object.oid, new_head);
1131 static int run_prepare_commit_msg_hook(struct repository *r,
1132 struct strbuf *msg,
1133 const char *commit)
1135 int ret = 0;
1136 const char *name, *arg1 = NULL, *arg2 = NULL;
1138 name = git_path_commit_editmsg();
1139 if (write_message(msg->buf, msg->len, name, 0))
1140 return -1;
1142 if (commit) {
1143 arg1 = "commit";
1144 arg2 = commit;
1145 } else {
1146 arg1 = "message";
1148 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1149 arg1, arg2, NULL))
1150 ret = error(_("'prepare-commit-msg' hook failed"));
1152 return ret;
1155 static const char implicit_ident_advice_noconfig[] =
1156 N_("Your name and email address were configured automatically based\n"
1157 "on your username and hostname. Please check that they are accurate.\n"
1158 "You can suppress this message by setting them explicitly. Run the\n"
1159 "following command and follow the instructions in your editor to edit\n"
1160 "your configuration file:\n"
1161 "\n"
1162 " git config --global --edit\n"
1163 "\n"
1164 "After doing this, you may fix the identity used for this commit with:\n"
1165 "\n"
1166 " git commit --amend --reset-author\n");
1168 static const char implicit_ident_advice_config[] =
1169 N_("Your name and email address were configured automatically based\n"
1170 "on your username and hostname. Please check that they are accurate.\n"
1171 "You can suppress this message by setting them explicitly:\n"
1172 "\n"
1173 " git config --global user.name \"Your Name\"\n"
1174 " git config --global user.email you@example.com\n"
1175 "\n"
1176 "After doing this, you may fix the identity used for this commit with:\n"
1177 "\n"
1178 " git commit --amend --reset-author\n");
1180 static const char *implicit_ident_advice(void)
1182 char *user_config = expand_user_path("~/.gitconfig", 0);
1183 char *xdg_config = xdg_config_home("config");
1184 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1186 free(user_config);
1187 free(xdg_config);
1189 if (config_exists)
1190 return _(implicit_ident_advice_config);
1191 else
1192 return _(implicit_ident_advice_noconfig);
1196 void print_commit_summary(struct repository *r,
1197 const char *prefix,
1198 const struct object_id *oid,
1199 unsigned int flags)
1201 struct rev_info rev;
1202 struct commit *commit;
1203 struct strbuf format = STRBUF_INIT;
1204 const char *head;
1205 struct pretty_print_context pctx = {0};
1206 struct strbuf author_ident = STRBUF_INIT;
1207 struct strbuf committer_ident = STRBUF_INIT;
1209 commit = lookup_commit(r, oid);
1210 if (!commit)
1211 die(_("couldn't look up newly created commit"));
1212 if (parse_commit(commit))
1213 die(_("could not parse newly created commit"));
1215 strbuf_addstr(&format, "format:%h] %s");
1217 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1218 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1219 if (strbuf_cmp(&author_ident, &committer_ident)) {
1220 strbuf_addstr(&format, "\n Author: ");
1221 strbuf_addbuf_percentquote(&format, &author_ident);
1223 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1224 struct strbuf date = STRBUF_INIT;
1226 format_commit_message(commit, "%ad", &date, &pctx);
1227 strbuf_addstr(&format, "\n Date: ");
1228 strbuf_addbuf_percentquote(&format, &date);
1229 strbuf_release(&date);
1231 if (!committer_ident_sufficiently_given()) {
1232 strbuf_addstr(&format, "\n Committer: ");
1233 strbuf_addbuf_percentquote(&format, &committer_ident);
1234 if (advice_implicit_identity) {
1235 strbuf_addch(&format, '\n');
1236 strbuf_addstr(&format, implicit_ident_advice());
1239 strbuf_release(&author_ident);
1240 strbuf_release(&committer_ident);
1242 repo_init_revisions(r, &rev, prefix);
1243 setup_revisions(0, NULL, &rev, NULL);
1245 rev.diff = 1;
1246 rev.diffopt.output_format =
1247 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1249 rev.verbose_header = 1;
1250 rev.show_root_diff = 1;
1251 get_commit_format(format.buf, &rev);
1252 rev.always_show_header = 0;
1253 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1254 rev.diffopt.break_opt = 0;
1255 diff_setup_done(&rev.diffopt);
1257 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1258 if (!head)
1259 die_errno(_("unable to resolve HEAD after creating commit"));
1260 if (!strcmp(head, "HEAD"))
1261 head = _("detached HEAD");
1262 else
1263 skip_prefix(head, "refs/heads/", &head);
1264 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1265 _(" (root-commit)") : "");
1267 if (!log_tree_commit(&rev, commit)) {
1268 rev.always_show_header = 1;
1269 rev.use_terminator = 1;
1270 log_tree_commit(&rev, commit);
1273 strbuf_release(&format);
1276 static int parse_head(struct repository *r, struct commit **head)
1278 struct commit *current_head;
1279 struct object_id oid;
1281 if (get_oid("HEAD", &oid)) {
1282 current_head = NULL;
1283 } else {
1284 current_head = lookup_commit_reference(r, &oid);
1285 if (!current_head)
1286 return error(_("could not parse HEAD"));
1287 if (!oideq(&oid, &current_head->object.oid)) {
1288 warning(_("HEAD %s is not a commit!"),
1289 oid_to_hex(&oid));
1291 if (parse_commit(current_head))
1292 return error(_("could not parse HEAD commit"));
1294 *head = current_head;
1296 return 0;
1300 * Try to commit without forking 'git commit'. In some cases we need
1301 * to run 'git commit' to display an error message
1303 * Returns:
1304 * -1 - error unable to commit
1305 * 0 - success
1306 * 1 - run 'git commit'
1308 static int try_to_commit(struct repository *r,
1309 struct strbuf *msg, const char *author,
1310 struct replay_opts *opts, unsigned int flags,
1311 struct object_id *oid)
1313 struct object_id tree;
1314 struct commit *current_head = NULL;
1315 struct commit_list *parents = NULL;
1316 struct commit_extra_header *extra = NULL;
1317 struct strbuf err = STRBUF_INIT;
1318 struct strbuf commit_msg = STRBUF_INIT;
1319 char *amend_author = NULL;
1320 const char *hook_commit = NULL;
1321 enum commit_msg_cleanup_mode cleanup;
1322 int res = 0;
1324 if (parse_head(r, &current_head))
1325 return -1;
1327 if (flags & AMEND_MSG) {
1328 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1329 const char *out_enc = get_commit_output_encoding();
1330 const char *message = logmsg_reencode(current_head, NULL,
1331 out_enc);
1333 if (!msg) {
1334 const char *orig_message = NULL;
1336 find_commit_subject(message, &orig_message);
1337 msg = &commit_msg;
1338 strbuf_addstr(msg, orig_message);
1339 hook_commit = "HEAD";
1341 author = amend_author = get_author(message);
1342 unuse_commit_buffer(current_head, message);
1343 if (!author) {
1344 res = error(_("unable to parse commit author"));
1345 goto out;
1347 parents = copy_commit_list(current_head->parents);
1348 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1349 } else if (current_head &&
1350 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1351 commit_list_insert(current_head, &parents);
1354 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1355 res = error(_("git write-tree failed to write a tree"));
1356 goto out;
1359 if (!(flags & ALLOW_EMPTY)) {
1360 struct commit *first_parent = current_head;
1362 if (flags & AMEND_MSG) {
1363 if (current_head->parents) {
1364 first_parent = current_head->parents->item;
1365 if (repo_parse_commit(r, first_parent)) {
1366 res = error(_("could not parse HEAD commit"));
1367 goto out;
1369 } else {
1370 first_parent = NULL;
1373 if (oideq(first_parent
1374 ? get_commit_tree_oid(first_parent)
1375 : the_hash_algo->empty_tree,
1376 &tree)) {
1377 res = 1; /* run 'git commit' to display error message */
1378 goto out;
1382 if (find_hook("prepare-commit-msg")) {
1383 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1384 if (res)
1385 goto out;
1386 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1387 2048) < 0) {
1388 res = error_errno(_("unable to read commit message "
1389 "from '%s'"),
1390 git_path_commit_editmsg());
1391 goto out;
1393 msg = &commit_msg;
1396 if (flags & CLEANUP_MSG)
1397 cleanup = COMMIT_MSG_CLEANUP_ALL;
1398 else if ((opts->signoff || opts->record_origin) &&
1399 !opts->explicit_cleanup)
1400 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1401 else
1402 cleanup = opts->default_msg_cleanup;
1404 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1405 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1406 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1407 res = 1; /* run 'git commit' to display error message */
1408 goto out;
1411 reset_ident_date();
1413 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1414 oid, author, opts->gpg_sign, extra)) {
1415 res = error(_("failed to write commit object"));
1416 goto out;
1419 if (update_head_with_reflog(current_head, oid,
1420 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1421 res = error("%s", err.buf);
1422 goto out;
1425 run_commit_hook(0, r->index_file, "post-commit", NULL);
1426 if (flags & AMEND_MSG)
1427 commit_post_rewrite(r, current_head, oid);
1429 out:
1430 free_commit_extra_headers(extra);
1431 strbuf_release(&err);
1432 strbuf_release(&commit_msg);
1433 free(amend_author);
1435 return res;
1438 static int write_rebase_head(struct object_id *oid)
1440 if (update_ref("rebase", "REBASE_HEAD", oid,
1441 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1442 return error(_("could not update %s"), "REBASE_HEAD");
1444 return 0;
1447 static int do_commit(struct repository *r,
1448 const char *msg_file, const char *author,
1449 struct replay_opts *opts, unsigned int flags,
1450 struct object_id *oid)
1452 int res = 1;
1454 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1455 struct object_id oid;
1456 struct strbuf sb = STRBUF_INIT;
1458 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1459 return error_errno(_("unable to read commit message "
1460 "from '%s'"),
1461 msg_file);
1463 res = try_to_commit(r, msg_file ? &sb : NULL,
1464 author, opts, flags, &oid);
1465 strbuf_release(&sb);
1466 if (!res) {
1467 unlink(git_path_cherry_pick_head(r));
1468 unlink(git_path_merge_msg(r));
1469 if (!is_rebase_i(opts))
1470 print_commit_summary(r, NULL, &oid,
1471 SUMMARY_SHOW_AUTHOR_DATE);
1472 return res;
1475 if (res == 1) {
1476 if (is_rebase_i(opts) && oid)
1477 if (write_rebase_head(oid))
1478 return -1;
1479 return run_git_commit(r, msg_file, opts, flags);
1482 return res;
1485 static int is_original_commit_empty(struct commit *commit)
1487 const struct object_id *ptree_oid;
1489 if (parse_commit(commit))
1490 return error(_("could not parse commit %s"),
1491 oid_to_hex(&commit->object.oid));
1492 if (commit->parents) {
1493 struct commit *parent = commit->parents->item;
1494 if (parse_commit(parent))
1495 return error(_("could not parse parent commit %s"),
1496 oid_to_hex(&parent->object.oid));
1497 ptree_oid = get_commit_tree_oid(parent);
1498 } else {
1499 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1502 return oideq(ptree_oid, get_commit_tree_oid(commit));
1506 * Should empty commits be allowed? Return status:
1507 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1508 * 0: Halt on empty commit
1509 * 1: Allow empty commit
1510 * 2: Drop empty commit
1512 static int allow_empty(struct repository *r,
1513 struct replay_opts *opts,
1514 struct commit *commit)
1516 int index_unchanged, originally_empty;
1519 * Four cases:
1521 * (1) we do not allow empty at all and error out.
1523 * (2) we allow ones that were initially empty, and
1524 * just drop the ones that become empty
1526 * (3) we allow ones that were initially empty, but
1527 * halt for the ones that become empty;
1529 * (4) we allow both.
1531 if (!opts->allow_empty)
1532 return 0; /* let "git commit" barf as necessary */
1534 index_unchanged = is_index_unchanged(r);
1535 if (index_unchanged < 0)
1536 return index_unchanged;
1537 if (!index_unchanged)
1538 return 0; /* we do not have to say --allow-empty */
1540 if (opts->keep_redundant_commits)
1541 return 1;
1543 originally_empty = is_original_commit_empty(commit);
1544 if (originally_empty < 0)
1545 return originally_empty;
1546 if (originally_empty)
1547 return 1;
1548 else if (opts->drop_redundant_commits)
1549 return 2;
1550 else
1551 return 0;
1554 static struct {
1555 char c;
1556 const char *str;
1557 } todo_command_info[] = {
1558 { 'p', "pick" },
1559 { 0, "revert" },
1560 { 'e', "edit" },
1561 { 'r', "reword" },
1562 { 'f', "fixup" },
1563 { 's', "squash" },
1564 { 'x', "exec" },
1565 { 'b', "break" },
1566 { 'l', "label" },
1567 { 't', "reset" },
1568 { 'm', "merge" },
1569 { 0, "noop" },
1570 { 'd', "drop" },
1571 { 0, NULL }
1574 static const char *command_to_string(const enum todo_command command)
1576 if (command < TODO_COMMENT)
1577 return todo_command_info[command].str;
1578 die(_("unknown command: %d"), command);
1581 static char command_to_char(const enum todo_command command)
1583 if (command < TODO_COMMENT)
1584 return todo_command_info[command].c;
1585 return comment_line_char;
1588 static int is_noop(const enum todo_command command)
1590 return TODO_NOOP <= command;
1593 static int is_fixup(enum todo_command command)
1595 return command == TODO_FIXUP || command == TODO_SQUASH;
1598 /* Does this command create a (non-merge) commit? */
1599 static int is_pick_or_similar(enum todo_command command)
1601 switch (command) {
1602 case TODO_PICK:
1603 case TODO_REVERT:
1604 case TODO_EDIT:
1605 case TODO_REWORD:
1606 case TODO_FIXUP:
1607 case TODO_SQUASH:
1608 return 1;
1609 default:
1610 return 0;
1614 static int update_squash_messages(struct repository *r,
1615 enum todo_command command,
1616 struct commit *commit,
1617 struct replay_opts *opts)
1619 struct strbuf buf = STRBUF_INIT;
1620 int res;
1621 const char *message, *body;
1622 const char *encoding = get_commit_output_encoding();
1624 if (opts->current_fixup_count > 0) {
1625 struct strbuf header = STRBUF_INIT;
1626 char *eol;
1628 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1629 return error(_("could not read '%s'"),
1630 rebase_path_squash_msg());
1632 eol = buf.buf[0] != comment_line_char ?
1633 buf.buf : strchrnul(buf.buf, '\n');
1635 strbuf_addf(&header, "%c ", comment_line_char);
1636 strbuf_addf(&header, _("This is a combination of %d commits."),
1637 opts->current_fixup_count + 2);
1638 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1639 strbuf_release(&header);
1640 } else {
1641 struct object_id head;
1642 struct commit *head_commit;
1643 const char *head_message, *body;
1645 if (get_oid("HEAD", &head))
1646 return error(_("need a HEAD to fixup"));
1647 if (!(head_commit = lookup_commit_reference(r, &head)))
1648 return error(_("could not read HEAD"));
1649 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1650 return error(_("could not read HEAD's commit message"));
1652 find_commit_subject(head_message, &body);
1653 if (write_message(body, strlen(body),
1654 rebase_path_fixup_msg(), 0)) {
1655 unuse_commit_buffer(head_commit, head_message);
1656 return error(_("cannot write '%s'"),
1657 rebase_path_fixup_msg());
1660 strbuf_addf(&buf, "%c ", comment_line_char);
1661 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1662 strbuf_addf(&buf, "\n%c ", comment_line_char);
1663 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1664 strbuf_addstr(&buf, "\n\n");
1665 strbuf_addstr(&buf, body);
1667 unuse_commit_buffer(head_commit, head_message);
1670 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1671 return error(_("could not read commit message of %s"),
1672 oid_to_hex(&commit->object.oid));
1673 find_commit_subject(message, &body);
1675 if (command == TODO_SQUASH) {
1676 unlink(rebase_path_fixup_msg());
1677 strbuf_addf(&buf, "\n%c ", comment_line_char);
1678 strbuf_addf(&buf, _("This is the commit message #%d:"),
1679 ++opts->current_fixup_count + 1);
1680 strbuf_addstr(&buf, "\n\n");
1681 strbuf_addstr(&buf, body);
1682 } else if (command == TODO_FIXUP) {
1683 strbuf_addf(&buf, "\n%c ", comment_line_char);
1684 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1685 ++opts->current_fixup_count + 1);
1686 strbuf_addstr(&buf, "\n\n");
1687 strbuf_add_commented_lines(&buf, body, strlen(body));
1688 } else
1689 return error(_("unknown command: %d"), command);
1690 unuse_commit_buffer(commit, message);
1692 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1693 strbuf_release(&buf);
1695 if (!res) {
1696 strbuf_addf(&opts->current_fixups, "%s%s %s",
1697 opts->current_fixups.len ? "\n" : "",
1698 command_to_string(command),
1699 oid_to_hex(&commit->object.oid));
1700 res = write_message(opts->current_fixups.buf,
1701 opts->current_fixups.len,
1702 rebase_path_current_fixups(), 0);
1705 return res;
1708 static void flush_rewritten_pending(void)
1710 struct strbuf buf = STRBUF_INIT;
1711 struct object_id newoid;
1712 FILE *out;
1714 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1715 !get_oid("HEAD", &newoid) &&
1716 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1717 char *bol = buf.buf, *eol;
1719 while (*bol) {
1720 eol = strchrnul(bol, '\n');
1721 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1722 bol, oid_to_hex(&newoid));
1723 if (!*eol)
1724 break;
1725 bol = eol + 1;
1727 fclose(out);
1728 unlink(rebase_path_rewritten_pending());
1730 strbuf_release(&buf);
1733 static void record_in_rewritten(struct object_id *oid,
1734 enum todo_command next_command)
1736 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1738 if (!out)
1739 return;
1741 fprintf(out, "%s\n", oid_to_hex(oid));
1742 fclose(out);
1744 if (!is_fixup(next_command))
1745 flush_rewritten_pending();
1748 static int do_pick_commit(struct repository *r,
1749 enum todo_command command,
1750 struct commit *commit,
1751 struct replay_opts *opts,
1752 int final_fixup, int *check_todo)
1754 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1755 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1756 struct object_id head;
1757 struct commit *base, *next, *parent;
1758 const char *base_label, *next_label;
1759 char *author = NULL;
1760 struct commit_message msg = { NULL, NULL, NULL, NULL };
1761 struct strbuf msgbuf = STRBUF_INIT;
1762 int res, unborn = 0, reword = 0, allow, drop_commit;
1764 if (opts->no_commit) {
1766 * We do not intend to commit immediately. We just want to
1767 * merge the differences in, so let's compute the tree
1768 * that represents the "current" state for merge-recursive
1769 * to work on.
1771 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1772 return error(_("your index file is unmerged."));
1773 } else {
1774 unborn = get_oid("HEAD", &head);
1775 /* Do we want to generate a root commit? */
1776 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1777 oideq(&head, &opts->squash_onto)) {
1778 if (is_fixup(command))
1779 return error(_("cannot fixup root commit"));
1780 flags |= CREATE_ROOT_COMMIT;
1781 unborn = 1;
1782 } else if (unborn)
1783 oidcpy(&head, the_hash_algo->empty_tree);
1784 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1785 NULL, 0))
1786 return error_dirty_index(r, opts);
1788 discard_index(r->index);
1790 if (!commit->parents)
1791 parent = NULL;
1792 else if (commit->parents->next) {
1793 /* Reverting or cherry-picking a merge commit */
1794 int cnt;
1795 struct commit_list *p;
1797 if (!opts->mainline)
1798 return error(_("commit %s is a merge but no -m option was given."),
1799 oid_to_hex(&commit->object.oid));
1801 for (cnt = 1, p = commit->parents;
1802 cnt != opts->mainline && p;
1803 cnt++)
1804 p = p->next;
1805 if (cnt != opts->mainline || !p)
1806 return error(_("commit %s does not have parent %d"),
1807 oid_to_hex(&commit->object.oid), opts->mainline);
1808 parent = p->item;
1809 } else if (1 < opts->mainline)
1811 * Non-first parent explicitly specified as mainline for
1812 * non-merge commit
1814 return error(_("commit %s does not have parent %d"),
1815 oid_to_hex(&commit->object.oid), opts->mainline);
1816 else
1817 parent = commit->parents->item;
1819 if (get_message(commit, &msg) != 0)
1820 return error(_("cannot get commit message for %s"),
1821 oid_to_hex(&commit->object.oid));
1823 if (opts->allow_ff && !is_fixup(command) &&
1824 ((parent && oideq(&parent->object.oid, &head)) ||
1825 (!parent && unborn))) {
1826 if (is_rebase_i(opts))
1827 write_author_script(msg.message);
1828 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1829 opts);
1830 if (res || command != TODO_REWORD)
1831 goto leave;
1832 reword = 1;
1833 msg_file = NULL;
1834 goto fast_forward_edit;
1836 if (parent && parse_commit(parent) < 0)
1837 /* TRANSLATORS: The first %s will be a "todo" command like
1838 "revert" or "pick", the second %s a SHA1. */
1839 return error(_("%s: cannot parse parent commit %s"),
1840 command_to_string(command),
1841 oid_to_hex(&parent->object.oid));
1844 * "commit" is an existing commit. We would want to apply
1845 * the difference it introduces since its first parent "prev"
1846 * on top of the current HEAD if we are cherry-pick. Or the
1847 * reverse of it if we are revert.
1850 if (command == TODO_REVERT) {
1851 base = commit;
1852 base_label = msg.label;
1853 next = parent;
1854 next_label = msg.parent_label;
1855 strbuf_addstr(&msgbuf, "Revert \"");
1856 strbuf_addstr(&msgbuf, msg.subject);
1857 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1858 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1860 if (commit->parents && commit->parents->next) {
1861 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1862 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1864 strbuf_addstr(&msgbuf, ".\n");
1865 } else {
1866 const char *p;
1868 base = parent;
1869 base_label = msg.parent_label;
1870 next = commit;
1871 next_label = msg.label;
1873 /* Append the commit log message to msgbuf. */
1874 if (find_commit_subject(msg.message, &p))
1875 strbuf_addstr(&msgbuf, p);
1877 if (opts->record_origin) {
1878 strbuf_complete_line(&msgbuf);
1879 if (!has_conforming_footer(&msgbuf, NULL, 0))
1880 strbuf_addch(&msgbuf, '\n');
1881 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1882 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1883 strbuf_addstr(&msgbuf, ")\n");
1885 if (!is_fixup(command))
1886 author = get_author(msg.message);
1889 if (command == TODO_REWORD)
1890 reword = 1;
1891 else if (is_fixup(command)) {
1892 if (update_squash_messages(r, command, commit, opts))
1893 return -1;
1894 flags |= AMEND_MSG;
1895 if (!final_fixup)
1896 msg_file = rebase_path_squash_msg();
1897 else if (file_exists(rebase_path_fixup_msg())) {
1898 flags |= CLEANUP_MSG;
1899 msg_file = rebase_path_fixup_msg();
1900 } else {
1901 const char *dest = git_path_squash_msg(r);
1902 unlink(dest);
1903 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1904 return error(_("could not rename '%s' to '%s'"),
1905 rebase_path_squash_msg(), dest);
1906 unlink(git_path_merge_msg(r));
1907 msg_file = dest;
1908 flags |= EDIT_MSG;
1912 if (opts->signoff && !is_fixup(command))
1913 append_signoff(&msgbuf, 0, 0);
1915 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1916 res = -1;
1917 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1918 res = do_recursive_merge(r, base, next, base_label, next_label,
1919 &head, &msgbuf, opts);
1920 if (res < 0)
1921 goto leave;
1923 res |= write_message(msgbuf.buf, msgbuf.len,
1924 git_path_merge_msg(r), 0);
1925 } else {
1926 struct commit_list *common = NULL;
1927 struct commit_list *remotes = NULL;
1929 res = write_message(msgbuf.buf, msgbuf.len,
1930 git_path_merge_msg(r), 0);
1932 commit_list_insert(base, &common);
1933 commit_list_insert(next, &remotes);
1934 res |= try_merge_command(r, opts->strategy,
1935 opts->xopts_nr, (const char **)opts->xopts,
1936 common, oid_to_hex(&head), remotes);
1937 free_commit_list(common);
1938 free_commit_list(remotes);
1940 strbuf_release(&msgbuf);
1943 * If the merge was clean or if it failed due to conflict, we write
1944 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1945 * However, if the merge did not even start, then we don't want to
1946 * write it at all.
1948 if ((command == TODO_PICK || command == TODO_REWORD ||
1949 command == TODO_EDIT) && !opts->no_commit &&
1950 (res == 0 || res == 1) &&
1951 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1952 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1953 res = -1;
1954 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1955 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1956 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1957 res = -1;
1959 if (res) {
1960 error(command == TODO_REVERT
1961 ? _("could not revert %s... %s")
1962 : _("could not apply %s... %s"),
1963 short_commit_name(commit), msg.subject);
1964 print_advice(r, res == 1, opts);
1965 repo_rerere(r, opts->allow_rerere_auto);
1966 goto leave;
1969 drop_commit = 0;
1970 allow = allow_empty(r, opts, commit);
1971 if (allow < 0) {
1972 res = allow;
1973 goto leave;
1974 } else if (allow == 1) {
1975 flags |= ALLOW_EMPTY;
1976 } else if (allow == 2) {
1977 drop_commit = 1;
1978 unlink(git_path_cherry_pick_head(r));
1979 unlink(git_path_merge_msg(r));
1980 fprintf(stderr,
1981 _("dropping %s %s -- patch contents already upstream\n"),
1982 oid_to_hex(&commit->object.oid), msg.subject);
1983 } /* else allow == 0 and there's nothing special to do */
1984 if (!opts->no_commit && !drop_commit) {
1985 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1986 res = do_commit(r, msg_file, author, opts, flags,
1987 commit? &commit->object.oid : NULL);
1988 else
1989 res = error(_("unable to parse commit author"));
1990 *check_todo = !!(flags & EDIT_MSG);
1991 if (!res && reword) {
1992 fast_forward_edit:
1993 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1994 VERIFY_MSG | AMEND_MSG |
1995 (flags & ALLOW_EMPTY));
1996 *check_todo = 1;
2001 if (!res && final_fixup) {
2002 unlink(rebase_path_fixup_msg());
2003 unlink(rebase_path_squash_msg());
2004 unlink(rebase_path_current_fixups());
2005 strbuf_reset(&opts->current_fixups);
2006 opts->current_fixup_count = 0;
2009 leave:
2010 free_message(commit, &msg);
2011 free(author);
2012 update_abort_safety_file();
2014 return res;
2017 static int prepare_revs(struct replay_opts *opts)
2020 * picking (but not reverting) ranges (but not individual revisions)
2021 * should be done in reverse
2023 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2024 opts->revs->reverse ^= 1;
2026 if (prepare_revision_walk(opts->revs))
2027 return error(_("revision walk setup failed"));
2029 return 0;
2032 static int read_and_refresh_cache(struct repository *r,
2033 struct replay_opts *opts)
2035 struct lock_file index_lock = LOCK_INIT;
2036 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2037 if (repo_read_index(r) < 0) {
2038 rollback_lock_file(&index_lock);
2039 return error(_("git %s: failed to read the index"),
2040 _(action_name(opts)));
2042 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2043 if (index_fd >= 0) {
2044 if (write_locked_index(r->index, &index_lock,
2045 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2046 return error(_("git %s: failed to refresh the index"),
2047 _(action_name(opts)));
2050 return 0;
2053 enum todo_item_flags {
2054 TODO_EDIT_MERGE_MSG = 1
2057 void todo_list_release(struct todo_list *todo_list)
2059 strbuf_release(&todo_list->buf);
2060 FREE_AND_NULL(todo_list->items);
2061 todo_list->nr = todo_list->alloc = 0;
2064 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2066 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2067 todo_list->total_nr++;
2068 return todo_list->items + todo_list->nr++;
2071 const char *todo_item_get_arg(struct todo_list *todo_list,
2072 struct todo_item *item)
2074 return todo_list->buf.buf + item->arg_offset;
2077 static int is_command(enum todo_command command, const char **bol)
2079 const char *str = todo_command_info[command].str;
2080 const char nick = todo_command_info[command].c;
2081 const char *p = *bol + 1;
2083 return skip_prefix(*bol, str, bol) ||
2084 ((nick && **bol == nick) &&
2085 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2086 (*bol = p));
2089 static int parse_insn_line(struct repository *r, struct todo_item *item,
2090 const char *buf, const char *bol, char *eol)
2092 struct object_id commit_oid;
2093 char *end_of_object_name;
2094 int i, saved, status, padding;
2096 item->flags = 0;
2098 /* left-trim */
2099 bol += strspn(bol, " \t");
2101 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2102 item->command = TODO_COMMENT;
2103 item->commit = NULL;
2104 item->arg_offset = bol - buf;
2105 item->arg_len = eol - bol;
2106 return 0;
2109 for (i = 0; i < TODO_COMMENT; i++)
2110 if (is_command(i, &bol)) {
2111 item->command = i;
2112 break;
2114 if (i >= TODO_COMMENT)
2115 return -1;
2117 /* Eat up extra spaces/ tabs before object name */
2118 padding = strspn(bol, " \t");
2119 bol += padding;
2121 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2122 if (bol != eol)
2123 return error(_("%s does not accept arguments: '%s'"),
2124 command_to_string(item->command), bol);
2125 item->commit = NULL;
2126 item->arg_offset = bol - buf;
2127 item->arg_len = eol - bol;
2128 return 0;
2131 if (!padding)
2132 return error(_("missing arguments for %s"),
2133 command_to_string(item->command));
2135 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2136 item->command == TODO_RESET) {
2137 item->commit = NULL;
2138 item->arg_offset = bol - buf;
2139 item->arg_len = (int)(eol - bol);
2140 return 0;
2143 if (item->command == TODO_MERGE) {
2144 if (skip_prefix(bol, "-C", &bol))
2145 bol += strspn(bol, " \t");
2146 else if (skip_prefix(bol, "-c", &bol)) {
2147 bol += strspn(bol, " \t");
2148 item->flags |= TODO_EDIT_MERGE_MSG;
2149 } else {
2150 item->flags |= TODO_EDIT_MERGE_MSG;
2151 item->commit = NULL;
2152 item->arg_offset = bol - buf;
2153 item->arg_len = (int)(eol - bol);
2154 return 0;
2158 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2159 saved = *end_of_object_name;
2160 *end_of_object_name = '\0';
2161 status = get_oid(bol, &commit_oid);
2162 if (status < 0)
2163 error(_("could not parse '%s'"), bol); /* return later */
2164 *end_of_object_name = saved;
2166 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2167 item->arg_offset = bol - buf;
2168 item->arg_len = (int)(eol - bol);
2170 if (status < 0)
2171 return status;
2173 item->commit = lookup_commit_reference(r, &commit_oid);
2174 return item->commit ? 0 : -1;
2177 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2179 const char *todo_file, *bol;
2180 struct strbuf buf = STRBUF_INIT;
2181 int ret = 0;
2183 todo_file = git_path_todo_file();
2184 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2185 if (errno == ENOENT || errno == ENOTDIR)
2186 return -1;
2187 else
2188 return error_errno("unable to open '%s'", todo_file);
2190 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2191 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2192 *action = REPLAY_PICK;
2193 else if (is_command(TODO_REVERT, &bol) &&
2194 (*bol == ' ' || *bol == '\t'))
2195 *action = REPLAY_REVERT;
2196 else
2197 ret = -1;
2199 strbuf_release(&buf);
2201 return ret;
2204 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2205 struct todo_list *todo_list)
2207 struct todo_item *item;
2208 char *p = buf, *next_p;
2209 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2211 todo_list->current = todo_list->nr = 0;
2213 for (i = 1; *p; i++, p = next_p) {
2214 char *eol = strchrnul(p, '\n');
2216 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2218 if (p != eol && eol[-1] == '\r')
2219 eol--; /* strip Carriage Return */
2221 item = append_new_todo(todo_list);
2222 item->offset_in_buf = p - todo_list->buf.buf;
2223 if (parse_insn_line(r, item, buf, p, eol)) {
2224 res = error(_("invalid line %d: %.*s"),
2225 i, (int)(eol - p), p);
2226 item->command = TODO_COMMENT + 1;
2227 item->arg_offset = p - buf;
2228 item->arg_len = (int)(eol - p);
2229 item->commit = NULL;
2232 if (fixup_okay)
2233 ; /* do nothing */
2234 else if (is_fixup(item->command))
2235 return error(_("cannot '%s' without a previous commit"),
2236 command_to_string(item->command));
2237 else if (!is_noop(item->command))
2238 fixup_okay = 1;
2241 return res;
2244 static int count_commands(struct todo_list *todo_list)
2246 int count = 0, i;
2248 for (i = 0; i < todo_list->nr; i++)
2249 if (todo_list->items[i].command != TODO_COMMENT)
2250 count++;
2252 return count;
2255 static int get_item_line_offset(struct todo_list *todo_list, int index)
2257 return index < todo_list->nr ?
2258 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2261 static const char *get_item_line(struct todo_list *todo_list, int index)
2263 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2266 static int get_item_line_length(struct todo_list *todo_list, int index)
2268 return get_item_line_offset(todo_list, index + 1)
2269 - get_item_line_offset(todo_list, index);
2272 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2274 int fd;
2275 ssize_t len;
2277 fd = open(path, O_RDONLY);
2278 if (fd < 0)
2279 return error_errno(_("could not open '%s'"), path);
2280 len = strbuf_read(sb, fd, 0);
2281 close(fd);
2282 if (len < 0)
2283 return error(_("could not read '%s'."), path);
2284 return len;
2287 static int have_finished_the_last_pick(void)
2289 struct strbuf buf = STRBUF_INIT;
2290 const char *eol;
2291 const char *todo_path = git_path_todo_file();
2292 int ret = 0;
2294 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2295 if (errno == ENOENT) {
2296 return 0;
2297 } else {
2298 error_errno("unable to open '%s'", todo_path);
2299 return 0;
2302 /* If there is only one line then we are done */
2303 eol = strchr(buf.buf, '\n');
2304 if (!eol || !eol[1])
2305 ret = 1;
2307 strbuf_release(&buf);
2309 return ret;
2312 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2314 struct replay_opts opts = REPLAY_OPTS_INIT;
2315 int need_cleanup = 0;
2317 if (file_exists(git_path_cherry_pick_head(r))) {
2318 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2319 warning(_("cancelling a cherry picking in progress"));
2320 opts.action = REPLAY_PICK;
2321 need_cleanup = 1;
2324 if (file_exists(git_path_revert_head(r))) {
2325 if (!unlink(git_path_revert_head(r)) && verbose)
2326 warning(_("cancelling a revert in progress"));
2327 opts.action = REPLAY_REVERT;
2328 need_cleanup = 1;
2331 if (!need_cleanup)
2332 return;
2334 if (!have_finished_the_last_pick())
2335 return;
2337 sequencer_remove_state(&opts);
2340 static void todo_list_write_total_nr(struct todo_list *todo_list)
2342 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2344 if (f) {
2345 fprintf(f, "%d\n", todo_list->total_nr);
2346 fclose(f);
2350 static int read_populate_todo(struct repository *r,
2351 struct todo_list *todo_list,
2352 struct replay_opts *opts)
2354 struct stat st;
2355 const char *todo_file = get_todo_path(opts);
2356 int res;
2358 strbuf_reset(&todo_list->buf);
2359 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2360 return -1;
2362 res = stat(todo_file, &st);
2363 if (res)
2364 return error(_("could not stat '%s'"), todo_file);
2365 fill_stat_data(&todo_list->stat, &st);
2367 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2368 if (res) {
2369 if (is_rebase_i(opts))
2370 return error(_("please fix this using "
2371 "'git rebase --edit-todo'."));
2372 return error(_("unusable instruction sheet: '%s'"), todo_file);
2375 if (!todo_list->nr &&
2376 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2377 return error(_("no commits parsed."));
2379 if (!is_rebase_i(opts)) {
2380 enum todo_command valid =
2381 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2382 int i;
2384 for (i = 0; i < todo_list->nr; i++)
2385 if (valid == todo_list->items[i].command)
2386 continue;
2387 else if (valid == TODO_PICK)
2388 return error(_("cannot cherry-pick during a revert."));
2389 else
2390 return error(_("cannot revert during a cherry-pick."));
2393 if (is_rebase_i(opts)) {
2394 struct todo_list done = TODO_LIST_INIT;
2396 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2397 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2398 todo_list->done_nr = count_commands(&done);
2399 else
2400 todo_list->done_nr = 0;
2402 todo_list->total_nr = todo_list->done_nr
2403 + count_commands(todo_list);
2404 todo_list_release(&done);
2406 todo_list_write_total_nr(todo_list);
2409 return 0;
2412 static int git_config_string_dup(char **dest,
2413 const char *var, const char *value)
2415 if (!value)
2416 return config_error_nonbool(var);
2417 free(*dest);
2418 *dest = xstrdup(value);
2419 return 0;
2422 static int populate_opts_cb(const char *key, const char *value, void *data)
2424 struct replay_opts *opts = data;
2425 int error_flag = 1;
2427 if (!value)
2428 error_flag = 0;
2429 else if (!strcmp(key, "options.no-commit"))
2430 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2431 else if (!strcmp(key, "options.edit"))
2432 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2433 else if (!strcmp(key, "options.allow-empty"))
2434 opts->allow_empty =
2435 git_config_bool_or_int(key, value, &error_flag);
2436 else if (!strcmp(key, "options.allow-empty-message"))
2437 opts->allow_empty_message =
2438 git_config_bool_or_int(key, value, &error_flag);
2439 else if (!strcmp(key, "options.keep-redundant-commits"))
2440 opts->keep_redundant_commits =
2441 git_config_bool_or_int(key, value, &error_flag);
2442 else if (!strcmp(key, "options.signoff"))
2443 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2444 else if (!strcmp(key, "options.record-origin"))
2445 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2446 else if (!strcmp(key, "options.allow-ff"))
2447 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2448 else if (!strcmp(key, "options.mainline"))
2449 opts->mainline = git_config_int(key, value);
2450 else if (!strcmp(key, "options.strategy"))
2451 git_config_string_dup(&opts->strategy, key, value);
2452 else if (!strcmp(key, "options.gpg-sign"))
2453 git_config_string_dup(&opts->gpg_sign, key, value);
2454 else if (!strcmp(key, "options.strategy-option")) {
2455 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2456 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2457 } else if (!strcmp(key, "options.allow-rerere-auto"))
2458 opts->allow_rerere_auto =
2459 git_config_bool_or_int(key, value, &error_flag) ?
2460 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2461 else if (!strcmp(key, "options.default-msg-cleanup")) {
2462 opts->explicit_cleanup = 1;
2463 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2464 } else
2465 return error(_("invalid key: %s"), key);
2467 if (!error_flag)
2468 return error(_("invalid value for %s: %s"), key, value);
2470 return 0;
2473 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2475 int i;
2476 char *strategy_opts_string = raw_opts;
2478 if (*strategy_opts_string == ' ')
2479 strategy_opts_string++;
2481 opts->xopts_nr = split_cmdline(strategy_opts_string,
2482 (const char ***)&opts->xopts);
2483 for (i = 0; i < opts->xopts_nr; i++) {
2484 const char *arg = opts->xopts[i];
2486 skip_prefix(arg, "--", &arg);
2487 opts->xopts[i] = xstrdup(arg);
2491 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2493 strbuf_reset(buf);
2494 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2495 return;
2496 opts->strategy = strbuf_detach(buf, NULL);
2497 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2498 return;
2500 parse_strategy_opts(opts, buf->buf);
2503 static int read_populate_opts(struct replay_opts *opts)
2505 if (is_rebase_i(opts)) {
2506 struct strbuf buf = STRBUF_INIT;
2508 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2509 if (!starts_with(buf.buf, "-S"))
2510 strbuf_reset(&buf);
2511 else {
2512 free(opts->gpg_sign);
2513 opts->gpg_sign = xstrdup(buf.buf + 2);
2515 strbuf_reset(&buf);
2518 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2519 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2520 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2521 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2522 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2523 strbuf_reset(&buf);
2526 if (file_exists(rebase_path_verbose()))
2527 opts->verbose = 1;
2529 if (file_exists(rebase_path_quiet()))
2530 opts->quiet = 1;
2532 if (file_exists(rebase_path_signoff())) {
2533 opts->allow_ff = 0;
2534 opts->signoff = 1;
2537 if (file_exists(rebase_path_reschedule_failed_exec()))
2538 opts->reschedule_failed_exec = 1;
2540 if (file_exists(rebase_path_drop_redundant_commits()))
2541 opts->drop_redundant_commits = 1;
2543 if (file_exists(rebase_path_keep_redundant_commits()))
2544 opts->keep_redundant_commits = 1;
2546 read_strategy_opts(opts, &buf);
2547 strbuf_release(&buf);
2549 if (read_oneliner(&opts->current_fixups,
2550 rebase_path_current_fixups(), 1)) {
2551 const char *p = opts->current_fixups.buf;
2552 opts->current_fixup_count = 1;
2553 while ((p = strchr(p, '\n'))) {
2554 opts->current_fixup_count++;
2555 p++;
2559 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2560 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2561 return error(_("unusable squash-onto"));
2562 opts->have_squash_onto = 1;
2565 return 0;
2568 if (!file_exists(git_path_opts_file()))
2569 return 0;
2571 * The function git_parse_source(), called from git_config_from_file(),
2572 * may die() in case of a syntactically incorrect file. We do not care
2573 * about this case, though, because we wrote that file ourselves, so we
2574 * are pretty certain that it is syntactically correct.
2576 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2577 return error(_("malformed options sheet: '%s'"),
2578 git_path_opts_file());
2579 return 0;
2582 static void write_strategy_opts(struct replay_opts *opts)
2584 int i;
2585 struct strbuf buf = STRBUF_INIT;
2587 for (i = 0; i < opts->xopts_nr; ++i)
2588 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2590 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2591 strbuf_release(&buf);
2594 int write_basic_state(struct replay_opts *opts, const char *head_name,
2595 struct commit *onto, const char *orig_head)
2597 if (head_name)
2598 write_file(rebase_path_head_name(), "%s\n", head_name);
2599 if (onto)
2600 write_file(rebase_path_onto(), "%s\n",
2601 oid_to_hex(&onto->object.oid));
2602 if (orig_head)
2603 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2605 if (opts->quiet)
2606 write_file(rebase_path_quiet(), "%s", "");
2607 if (opts->verbose)
2608 write_file(rebase_path_verbose(), "%s", "");
2609 if (opts->strategy)
2610 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2611 if (opts->xopts_nr > 0)
2612 write_strategy_opts(opts);
2614 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2615 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2616 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2617 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2619 if (opts->gpg_sign)
2620 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2621 if (opts->signoff)
2622 write_file(rebase_path_signoff(), "--signoff\n");
2623 if (opts->drop_redundant_commits)
2624 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2625 if (opts->keep_redundant_commits)
2626 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2627 if (opts->reschedule_failed_exec)
2628 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2630 return 0;
2633 static int walk_revs_populate_todo(struct todo_list *todo_list,
2634 struct replay_opts *opts)
2636 enum todo_command command = opts->action == REPLAY_PICK ?
2637 TODO_PICK : TODO_REVERT;
2638 const char *command_string = todo_command_info[command].str;
2639 const char *encoding;
2640 struct commit *commit;
2642 if (prepare_revs(opts))
2643 return -1;
2645 encoding = get_log_output_encoding();
2647 while ((commit = get_revision(opts->revs))) {
2648 struct todo_item *item = append_new_todo(todo_list);
2649 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2650 const char *subject;
2651 int subject_len;
2653 item->command = command;
2654 item->commit = commit;
2655 item->arg_offset = 0;
2656 item->arg_len = 0;
2657 item->offset_in_buf = todo_list->buf.len;
2658 subject_len = find_commit_subject(commit_buffer, &subject);
2659 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2660 short_commit_name(commit), subject_len, subject);
2661 unuse_commit_buffer(commit, commit_buffer);
2664 if (!todo_list->nr)
2665 return error(_("empty commit set passed"));
2667 return 0;
2670 static int create_seq_dir(struct repository *r)
2672 enum replay_action action;
2673 const char *in_progress_error = NULL;
2674 const char *in_progress_advice = NULL;
2675 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2676 file_exists(git_path_cherry_pick_head(r));
2678 if (!sequencer_get_last_command(r, &action)) {
2679 switch (action) {
2680 case REPLAY_REVERT:
2681 in_progress_error = _("revert is already in progress");
2682 in_progress_advice =
2683 _("try \"git revert (--continue | %s--abort | --quit)\"");
2684 break;
2685 case REPLAY_PICK:
2686 in_progress_error = _("cherry-pick is already in progress");
2687 in_progress_advice =
2688 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2689 break;
2690 default:
2691 BUG("unexpected action in create_seq_dir");
2694 if (in_progress_error) {
2695 error("%s", in_progress_error);
2696 if (advice_sequencer_in_use)
2697 advise(in_progress_advice,
2698 advise_skip ? "--skip | " : "");
2699 return -1;
2701 if (mkdir(git_path_seq_dir(), 0777) < 0)
2702 return error_errno(_("could not create sequencer directory '%s'"),
2703 git_path_seq_dir());
2705 return 0;
2708 static int save_head(const char *head)
2710 struct lock_file head_lock = LOCK_INIT;
2711 struct strbuf buf = STRBUF_INIT;
2712 int fd;
2713 ssize_t written;
2715 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2716 if (fd < 0)
2717 return error_errno(_("could not lock HEAD"));
2718 strbuf_addf(&buf, "%s\n", head);
2719 written = write_in_full(fd, buf.buf, buf.len);
2720 strbuf_release(&buf);
2721 if (written < 0) {
2722 error_errno(_("could not write to '%s'"), git_path_head_file());
2723 rollback_lock_file(&head_lock);
2724 return -1;
2726 if (commit_lock_file(&head_lock) < 0)
2727 return error(_("failed to finalize '%s'"), git_path_head_file());
2728 return 0;
2731 static int rollback_is_safe(void)
2733 struct strbuf sb = STRBUF_INIT;
2734 struct object_id expected_head, actual_head;
2736 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2737 strbuf_trim(&sb);
2738 if (get_oid_hex(sb.buf, &expected_head)) {
2739 strbuf_release(&sb);
2740 die(_("could not parse %s"), git_path_abort_safety_file());
2742 strbuf_release(&sb);
2744 else if (errno == ENOENT)
2745 oidclr(&expected_head);
2746 else
2747 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2749 if (get_oid("HEAD", &actual_head))
2750 oidclr(&actual_head);
2752 return oideq(&actual_head, &expected_head);
2755 static int reset_merge(const struct object_id *oid)
2757 int ret;
2758 struct argv_array argv = ARGV_ARRAY_INIT;
2760 argv_array_pushl(&argv, "reset", "--merge", NULL);
2762 if (!is_null_oid(oid))
2763 argv_array_push(&argv, oid_to_hex(oid));
2765 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2766 argv_array_clear(&argv);
2768 return ret;
2771 static int rollback_single_pick(struct repository *r)
2773 struct object_id head_oid;
2775 if (!file_exists(git_path_cherry_pick_head(r)) &&
2776 !file_exists(git_path_revert_head(r)))
2777 return error(_("no cherry-pick or revert in progress"));
2778 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2779 return error(_("cannot resolve HEAD"));
2780 if (is_null_oid(&head_oid))
2781 return error(_("cannot abort from a branch yet to be born"));
2782 return reset_merge(&head_oid);
2785 static int skip_single_pick(void)
2787 struct object_id head;
2789 if (read_ref_full("HEAD", 0, &head, NULL))
2790 return error(_("cannot resolve HEAD"));
2791 return reset_merge(&head);
2794 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2796 FILE *f;
2797 struct object_id oid;
2798 struct strbuf buf = STRBUF_INIT;
2799 const char *p;
2801 f = fopen(git_path_head_file(), "r");
2802 if (!f && errno == ENOENT) {
2804 * There is no multiple-cherry-pick in progress.
2805 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2806 * a single-cherry-pick in progress, abort that.
2808 return rollback_single_pick(r);
2810 if (!f)
2811 return error_errno(_("cannot open '%s'"), git_path_head_file());
2812 if (strbuf_getline_lf(&buf, f)) {
2813 error(_("cannot read '%s': %s"), git_path_head_file(),
2814 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2815 fclose(f);
2816 goto fail;
2818 fclose(f);
2819 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2820 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2821 git_path_head_file());
2822 goto fail;
2824 if (is_null_oid(&oid)) {
2825 error(_("cannot abort from a branch yet to be born"));
2826 goto fail;
2829 if (!rollback_is_safe()) {
2830 /* Do not error, just do not rollback */
2831 warning(_("You seem to have moved HEAD. "
2832 "Not rewinding, check your HEAD!"));
2833 } else
2834 if (reset_merge(&oid))
2835 goto fail;
2836 strbuf_release(&buf);
2837 return sequencer_remove_state(opts);
2838 fail:
2839 strbuf_release(&buf);
2840 return -1;
2843 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2845 enum replay_action action = -1;
2846 sequencer_get_last_command(r, &action);
2849 * Check whether the subcommand requested to skip the commit is actually
2850 * in progress and that it's safe to skip the commit.
2852 * opts->action tells us which subcommand requested to skip the commit.
2853 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2854 * action is in progress and we can skip the commit.
2856 * Otherwise we check that the last instruction was related to the
2857 * particular subcommand we're trying to execute and barf if that's not
2858 * the case.
2860 * Finally we check that the rollback is "safe", i.e., has the HEAD
2861 * moved? In this case, it doesn't make sense to "reset the merge" and
2862 * "skip the commit" as the user already handled this by committing. But
2863 * we'd not want to barf here, instead give advice on how to proceed. We
2864 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2865 * it gets removed when the user commits, so if it still exists we're
2866 * sure the user can't have committed before.
2868 switch (opts->action) {
2869 case REPLAY_REVERT:
2870 if (!file_exists(git_path_revert_head(r))) {
2871 if (action != REPLAY_REVERT)
2872 return error(_("no revert in progress"));
2873 if (!rollback_is_safe())
2874 goto give_advice;
2876 break;
2877 case REPLAY_PICK:
2878 if (!file_exists(git_path_cherry_pick_head(r))) {
2879 if (action != REPLAY_PICK)
2880 return error(_("no cherry-pick in progress"));
2881 if (!rollback_is_safe())
2882 goto give_advice;
2884 break;
2885 default:
2886 BUG("unexpected action in sequencer_skip");
2889 if (skip_single_pick())
2890 return error(_("failed to skip the commit"));
2891 if (!is_directory(git_path_seq_dir()))
2892 return 0;
2894 return sequencer_continue(r, opts);
2896 give_advice:
2897 error(_("there is nothing to skip"));
2899 if (advice_resolve_conflict) {
2900 advise(_("have you committed already?\n"
2901 "try \"git %s --continue\""),
2902 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2904 return -1;
2907 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2909 struct lock_file todo_lock = LOCK_INIT;
2910 const char *todo_path = get_todo_path(opts);
2911 int next = todo_list->current, offset, fd;
2914 * rebase -i writes "git-rebase-todo" without the currently executing
2915 * command, appending it to "done" instead.
2917 if (is_rebase_i(opts))
2918 next++;
2920 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2921 if (fd < 0)
2922 return error_errno(_("could not lock '%s'"), todo_path);
2923 offset = get_item_line_offset(todo_list, next);
2924 if (write_in_full(fd, todo_list->buf.buf + offset,
2925 todo_list->buf.len - offset) < 0)
2926 return error_errno(_("could not write to '%s'"), todo_path);
2927 if (commit_lock_file(&todo_lock) < 0)
2928 return error(_("failed to finalize '%s'"), todo_path);
2930 if (is_rebase_i(opts) && next > 0) {
2931 const char *done = rebase_path_done();
2932 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2933 int ret = 0;
2935 if (fd < 0)
2936 return 0;
2937 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2938 get_item_line_length(todo_list, next - 1))
2939 < 0)
2940 ret = error_errno(_("could not write to '%s'"), done);
2941 if (close(fd) < 0)
2942 ret = error_errno(_("failed to finalize '%s'"), done);
2943 return ret;
2945 return 0;
2948 static int save_opts(struct replay_opts *opts)
2950 const char *opts_file = git_path_opts_file();
2951 int res = 0;
2953 if (opts->no_commit)
2954 res |= git_config_set_in_file_gently(opts_file,
2955 "options.no-commit", "true");
2956 if (opts->edit)
2957 res |= git_config_set_in_file_gently(opts_file,
2958 "options.edit", "true");
2959 if (opts->allow_empty)
2960 res |= git_config_set_in_file_gently(opts_file,
2961 "options.allow-empty", "true");
2962 if (opts->allow_empty_message)
2963 res |= git_config_set_in_file_gently(opts_file,
2964 "options.allow-empty-message", "true");
2965 if (opts->keep_redundant_commits)
2966 res |= git_config_set_in_file_gently(opts_file,
2967 "options.keep-redundant-commits", "true");
2968 if (opts->signoff)
2969 res |= git_config_set_in_file_gently(opts_file,
2970 "options.signoff", "true");
2971 if (opts->record_origin)
2972 res |= git_config_set_in_file_gently(opts_file,
2973 "options.record-origin", "true");
2974 if (opts->allow_ff)
2975 res |= git_config_set_in_file_gently(opts_file,
2976 "options.allow-ff", "true");
2977 if (opts->mainline) {
2978 struct strbuf buf = STRBUF_INIT;
2979 strbuf_addf(&buf, "%d", opts->mainline);
2980 res |= git_config_set_in_file_gently(opts_file,
2981 "options.mainline", buf.buf);
2982 strbuf_release(&buf);
2984 if (opts->strategy)
2985 res |= git_config_set_in_file_gently(opts_file,
2986 "options.strategy", opts->strategy);
2987 if (opts->gpg_sign)
2988 res |= git_config_set_in_file_gently(opts_file,
2989 "options.gpg-sign", opts->gpg_sign);
2990 if (opts->xopts) {
2991 int i;
2992 for (i = 0; i < opts->xopts_nr; i++)
2993 res |= git_config_set_multivar_in_file_gently(opts_file,
2994 "options.strategy-option",
2995 opts->xopts[i], "^$", 0);
2997 if (opts->allow_rerere_auto)
2998 res |= git_config_set_in_file_gently(opts_file,
2999 "options.allow-rerere-auto",
3000 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3001 "true" : "false");
3003 if (opts->explicit_cleanup)
3004 res |= git_config_set_in_file_gently(opts_file,
3005 "options.default-msg-cleanup",
3006 describe_cleanup_mode(opts->default_msg_cleanup));
3007 return res;
3010 static int make_patch(struct repository *r,
3011 struct commit *commit,
3012 struct replay_opts *opts)
3014 struct strbuf buf = STRBUF_INIT;
3015 struct rev_info log_tree_opt;
3016 const char *subject, *p;
3017 int res = 0;
3019 p = short_commit_name(commit);
3020 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3021 return -1;
3022 res |= write_rebase_head(&commit->object.oid);
3024 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3025 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3026 repo_init_revisions(r, &log_tree_opt, NULL);
3027 log_tree_opt.abbrev = 0;
3028 log_tree_opt.diff = 1;
3029 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3030 log_tree_opt.disable_stdin = 1;
3031 log_tree_opt.no_commit_id = 1;
3032 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3033 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3034 if (!log_tree_opt.diffopt.file)
3035 res |= error_errno(_("could not open '%s'"), buf.buf);
3036 else {
3037 res |= log_tree_commit(&log_tree_opt, commit);
3038 fclose(log_tree_opt.diffopt.file);
3040 strbuf_reset(&buf);
3042 strbuf_addf(&buf, "%s/message", get_dir(opts));
3043 if (!file_exists(buf.buf)) {
3044 const char *encoding = get_commit_output_encoding();
3045 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3046 find_commit_subject(commit_buffer, &subject);
3047 res |= write_message(subject, strlen(subject), buf.buf, 1);
3048 unuse_commit_buffer(commit, commit_buffer);
3050 strbuf_release(&buf);
3052 return res;
3055 static int intend_to_amend(void)
3057 struct object_id head;
3058 char *p;
3060 if (get_oid("HEAD", &head))
3061 return error(_("cannot read HEAD"));
3063 p = oid_to_hex(&head);
3064 return write_message(p, strlen(p), rebase_path_amend(), 1);
3067 static int error_with_patch(struct repository *r,
3068 struct commit *commit,
3069 const char *subject, int subject_len,
3070 struct replay_opts *opts,
3071 int exit_code, int to_amend)
3073 if (commit) {
3074 if (make_patch(r, commit, opts))
3075 return -1;
3076 } else if (copy_file(rebase_path_message(),
3077 git_path_merge_msg(r), 0666))
3078 return error(_("unable to copy '%s' to '%s'"),
3079 git_path_merge_msg(r), rebase_path_message());
3081 if (to_amend) {
3082 if (intend_to_amend())
3083 return -1;
3085 fprintf(stderr,
3086 _("You can amend the commit now, with\n"
3087 "\n"
3088 " git commit --amend %s\n"
3089 "\n"
3090 "Once you are satisfied with your changes, run\n"
3091 "\n"
3092 " git rebase --continue\n"),
3093 gpg_sign_opt_quoted(opts));
3094 } else if (exit_code) {
3095 if (commit)
3096 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3097 short_commit_name(commit), subject_len, subject);
3098 else
3100 * We don't have the hash of the parent so
3101 * just print the line from the todo file.
3103 fprintf_ln(stderr, _("Could not merge %.*s"),
3104 subject_len, subject);
3107 return exit_code;
3110 static int error_failed_squash(struct repository *r,
3111 struct commit *commit,
3112 struct replay_opts *opts,
3113 int subject_len,
3114 const char *subject)
3116 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3117 return error(_("could not copy '%s' to '%s'"),
3118 rebase_path_squash_msg(), rebase_path_message());
3119 unlink(git_path_merge_msg(r));
3120 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3121 return error(_("could not copy '%s' to '%s'"),
3122 rebase_path_message(),
3123 git_path_merge_msg(r));
3124 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3127 static int do_exec(struct repository *r, const char *command_line)
3129 struct argv_array child_env = ARGV_ARRAY_INIT;
3130 const char *child_argv[] = { NULL, NULL };
3131 int dirty, status;
3133 fprintf(stderr, _("Executing: %s\n"), command_line);
3134 child_argv[0] = command_line;
3135 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3136 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3137 absolute_path(get_git_work_tree()));
3138 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3139 child_env.argv);
3141 /* force re-reading of the cache */
3142 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3143 return error(_("could not read index"));
3145 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3147 if (status) {
3148 warning(_("execution failed: %s\n%s"
3149 "You can fix the problem, and then run\n"
3150 "\n"
3151 " git rebase --continue\n"
3152 "\n"),
3153 command_line,
3154 dirty ? N_("and made changes to the index and/or the "
3155 "working tree\n") : "");
3156 if (status == 127)
3157 /* command not found */
3158 status = 1;
3159 } else if (dirty) {
3160 warning(_("execution succeeded: %s\nbut "
3161 "left changes to the index and/or the working tree\n"
3162 "Commit or stash your changes, and then run\n"
3163 "\n"
3164 " git rebase --continue\n"
3165 "\n"), command_line);
3166 status = 1;
3169 argv_array_clear(&child_env);
3171 return status;
3174 static int safe_append(const char *filename, const char *fmt, ...)
3176 va_list ap;
3177 struct lock_file lock = LOCK_INIT;
3178 int fd = hold_lock_file_for_update(&lock, filename,
3179 LOCK_REPORT_ON_ERROR);
3180 struct strbuf buf = STRBUF_INIT;
3182 if (fd < 0)
3183 return -1;
3185 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3186 error_errno(_("could not read '%s'"), filename);
3187 rollback_lock_file(&lock);
3188 return -1;
3190 strbuf_complete(&buf, '\n');
3191 va_start(ap, fmt);
3192 strbuf_vaddf(&buf, fmt, ap);
3193 va_end(ap);
3195 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3196 error_errno(_("could not write to '%s'"), filename);
3197 strbuf_release(&buf);
3198 rollback_lock_file(&lock);
3199 return -1;
3201 if (commit_lock_file(&lock) < 0) {
3202 strbuf_release(&buf);
3203 rollback_lock_file(&lock);
3204 return error(_("failed to finalize '%s'"), filename);
3207 strbuf_release(&buf);
3208 return 0;
3211 static int do_label(struct repository *r, const char *name, int len)
3213 struct ref_store *refs = get_main_ref_store(r);
3214 struct ref_transaction *transaction;
3215 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3216 struct strbuf msg = STRBUF_INIT;
3217 int ret = 0;
3218 struct object_id head_oid;
3220 if (len == 1 && *name == '#')
3221 return error(_("illegal label name: '%.*s'"), len, name);
3223 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3224 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3226 transaction = ref_store_transaction_begin(refs, &err);
3227 if (!transaction) {
3228 error("%s", err.buf);
3229 ret = -1;
3230 } else if (get_oid("HEAD", &head_oid)) {
3231 error(_("could not read HEAD"));
3232 ret = -1;
3233 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3234 NULL, 0, msg.buf, &err) < 0 ||
3235 ref_transaction_commit(transaction, &err)) {
3236 error("%s", err.buf);
3237 ret = -1;
3239 ref_transaction_free(transaction);
3240 strbuf_release(&err);
3241 strbuf_release(&msg);
3243 if (!ret)
3244 ret = safe_append(rebase_path_refs_to_delete(),
3245 "%s\n", ref_name.buf);
3246 strbuf_release(&ref_name);
3248 return ret;
3251 static const char *reflog_message(struct replay_opts *opts,
3252 const char *sub_action, const char *fmt, ...);
3254 static int do_reset(struct repository *r,
3255 const char *name, int len,
3256 struct replay_opts *opts)
3258 struct strbuf ref_name = STRBUF_INIT;
3259 struct object_id oid;
3260 struct lock_file lock = LOCK_INIT;
3261 struct tree_desc desc;
3262 struct tree *tree;
3263 struct unpack_trees_options unpack_tree_opts;
3264 int ret = 0;
3266 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3267 return -1;
3269 if (len == 10 && !strncmp("[new root]", name, len)) {
3270 if (!opts->have_squash_onto) {
3271 const char *hex;
3272 if (commit_tree("", 0, the_hash_algo->empty_tree,
3273 NULL, &opts->squash_onto,
3274 NULL, NULL))
3275 return error(_("writing fake root commit"));
3276 opts->have_squash_onto = 1;
3277 hex = oid_to_hex(&opts->squash_onto);
3278 if (write_message(hex, strlen(hex),
3279 rebase_path_squash_onto(), 0))
3280 return error(_("writing squash-onto"));
3282 oidcpy(&oid, &opts->squash_onto);
3283 } else {
3284 int i;
3286 /* Determine the length of the label */
3287 for (i = 0; i < len; i++)
3288 if (isspace(name[i]))
3289 break;
3290 len = i;
3292 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3293 if (get_oid(ref_name.buf, &oid) &&
3294 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3295 error(_("could not read '%s'"), ref_name.buf);
3296 rollback_lock_file(&lock);
3297 strbuf_release(&ref_name);
3298 return -1;
3302 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3303 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3304 unpack_tree_opts.head_idx = 1;
3305 unpack_tree_opts.src_index = r->index;
3306 unpack_tree_opts.dst_index = r->index;
3307 unpack_tree_opts.fn = oneway_merge;
3308 unpack_tree_opts.merge = 1;
3309 unpack_tree_opts.update = 1;
3310 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3312 if (repo_read_index_unmerged(r)) {
3313 rollback_lock_file(&lock);
3314 strbuf_release(&ref_name);
3315 return error_resolve_conflict(_(action_name(opts)));
3318 if (!fill_tree_descriptor(r, &desc, &oid)) {
3319 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3320 rollback_lock_file(&lock);
3321 free((void *)desc.buffer);
3322 strbuf_release(&ref_name);
3323 return -1;
3326 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3327 rollback_lock_file(&lock);
3328 free((void *)desc.buffer);
3329 strbuf_release(&ref_name);
3330 return -1;
3333 tree = parse_tree_indirect(&oid);
3334 prime_cache_tree(r, r->index, tree);
3336 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3337 ret = error(_("could not write index"));
3338 free((void *)desc.buffer);
3340 if (!ret)
3341 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3342 len, name), "HEAD", &oid,
3343 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3345 strbuf_release(&ref_name);
3346 return ret;
3349 static struct commit *lookup_label(const char *label, int len,
3350 struct strbuf *buf)
3352 struct commit *commit;
3354 strbuf_reset(buf);
3355 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3356 commit = lookup_commit_reference_by_name(buf->buf);
3357 if (!commit) {
3358 /* fall back to non-rewritten ref or commit */
3359 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3360 commit = lookup_commit_reference_by_name(buf->buf);
3363 if (!commit)
3364 error(_("could not resolve '%s'"), buf->buf);
3366 return commit;
3369 static int do_merge(struct repository *r,
3370 struct commit *commit,
3371 const char *arg, int arg_len,
3372 int flags, struct replay_opts *opts)
3374 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3375 EDIT_MSG | VERIFY_MSG : 0;
3376 struct strbuf ref_name = STRBUF_INIT;
3377 struct commit *head_commit, *merge_commit, *i;
3378 struct commit_list *bases, *j, *reversed = NULL;
3379 struct commit_list *to_merge = NULL, **tail = &to_merge;
3380 const char *strategy = !opts->xopts_nr &&
3381 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3382 NULL : opts->strategy;
3383 struct merge_options o;
3384 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3385 static struct lock_file lock;
3386 const char *p;
3388 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3389 ret = -1;
3390 goto leave_merge;
3393 head_commit = lookup_commit_reference_by_name("HEAD");
3394 if (!head_commit) {
3395 ret = error(_("cannot merge without a current revision"));
3396 goto leave_merge;
3400 * For octopus merges, the arg starts with the list of revisions to be
3401 * merged. The list is optionally followed by '#' and the oneline.
3403 merge_arg_len = oneline_offset = arg_len;
3404 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3405 if (!*p)
3406 break;
3407 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3408 p += 1 + strspn(p + 1, " \t\n");
3409 oneline_offset = p - arg;
3410 break;
3412 k = strcspn(p, " \t\n");
3413 if (!k)
3414 continue;
3415 merge_commit = lookup_label(p, k, &ref_name);
3416 if (!merge_commit) {
3417 ret = error(_("unable to parse '%.*s'"), k, p);
3418 goto leave_merge;
3420 tail = &commit_list_insert(merge_commit, tail)->next;
3421 p += k;
3422 merge_arg_len = p - arg;
3425 if (!to_merge) {
3426 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3427 goto leave_merge;
3430 if (opts->have_squash_onto &&
3431 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3433 * When the user tells us to "merge" something into a
3434 * "[new root]", let's simply fast-forward to the merge head.
3436 rollback_lock_file(&lock);
3437 if (to_merge->next)
3438 ret = error(_("octopus merge cannot be executed on "
3439 "top of a [new root]"));
3440 else
3441 ret = fast_forward_to(r, &to_merge->item->object.oid,
3442 &head_commit->object.oid, 0,
3443 opts);
3444 goto leave_merge;
3447 if (commit) {
3448 const char *encoding = get_commit_output_encoding();
3449 const char *message = logmsg_reencode(commit, NULL, encoding);
3450 const char *body;
3451 int len;
3453 if (!message) {
3454 ret = error(_("could not get commit message of '%s'"),
3455 oid_to_hex(&commit->object.oid));
3456 goto leave_merge;
3458 write_author_script(message);
3459 find_commit_subject(message, &body);
3460 len = strlen(body);
3461 ret = write_message(body, len, git_path_merge_msg(r), 0);
3462 unuse_commit_buffer(commit, message);
3463 if (ret) {
3464 error_errno(_("could not write '%s'"),
3465 git_path_merge_msg(r));
3466 goto leave_merge;
3468 } else {
3469 struct strbuf buf = STRBUF_INIT;
3470 int len;
3472 strbuf_addf(&buf, "author %s", git_author_info(0));
3473 write_author_script(buf.buf);
3474 strbuf_reset(&buf);
3476 if (oneline_offset < arg_len) {
3477 p = arg + oneline_offset;
3478 len = arg_len - oneline_offset;
3479 } else {
3480 strbuf_addf(&buf, "Merge %s '%.*s'",
3481 to_merge->next ? "branches" : "branch",
3482 merge_arg_len, arg);
3483 p = buf.buf;
3484 len = buf.len;
3487 ret = write_message(p, len, git_path_merge_msg(r), 0);
3488 strbuf_release(&buf);
3489 if (ret) {
3490 error_errno(_("could not write '%s'"),
3491 git_path_merge_msg(r));
3492 goto leave_merge;
3497 * If HEAD is not identical to the first parent of the original merge
3498 * commit, we cannot fast-forward.
3500 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3501 oideq(&commit->parents->item->object.oid,
3502 &head_commit->object.oid);
3505 * If any merge head is different from the original one, we cannot
3506 * fast-forward.
3508 if (can_fast_forward) {
3509 struct commit_list *p = commit->parents->next;
3511 for (j = to_merge; j && p; j = j->next, p = p->next)
3512 if (!oideq(&j->item->object.oid,
3513 &p->item->object.oid)) {
3514 can_fast_forward = 0;
3515 break;
3518 * If the number of merge heads differs from the original merge
3519 * commit, we cannot fast-forward.
3521 if (j || p)
3522 can_fast_forward = 0;
3525 if (can_fast_forward) {
3526 rollback_lock_file(&lock);
3527 ret = fast_forward_to(r, &commit->object.oid,
3528 &head_commit->object.oid, 0, opts);
3529 if (flags & TODO_EDIT_MERGE_MSG) {
3530 run_commit_flags |= AMEND_MSG;
3531 goto fast_forward_edit;
3533 goto leave_merge;
3536 if (strategy || to_merge->next) {
3537 /* Octopus merge */
3538 struct child_process cmd = CHILD_PROCESS_INIT;
3540 if (read_env_script(&cmd.env_array)) {
3541 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3543 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3544 goto leave_merge;
3547 cmd.git_cmd = 1;
3548 argv_array_push(&cmd.args, "merge");
3549 argv_array_push(&cmd.args, "-s");
3550 if (!strategy)
3551 argv_array_push(&cmd.args, "octopus");
3552 else {
3553 argv_array_push(&cmd.args, strategy);
3554 for (k = 0; k < opts->xopts_nr; k++)
3555 argv_array_pushf(&cmd.args,
3556 "-X%s", opts->xopts[k]);
3558 argv_array_push(&cmd.args, "--no-edit");
3559 argv_array_push(&cmd.args, "--no-ff");
3560 argv_array_push(&cmd.args, "--no-log");
3561 argv_array_push(&cmd.args, "--no-stat");
3562 argv_array_push(&cmd.args, "-F");
3563 argv_array_push(&cmd.args, git_path_merge_msg(r));
3564 if (opts->gpg_sign)
3565 argv_array_push(&cmd.args, opts->gpg_sign);
3567 /* Add the tips to be merged */
3568 for (j = to_merge; j; j = j->next)
3569 argv_array_push(&cmd.args,
3570 oid_to_hex(&j->item->object.oid));
3572 strbuf_release(&ref_name);
3573 unlink(git_path_cherry_pick_head(r));
3574 rollback_lock_file(&lock);
3576 rollback_lock_file(&lock);
3577 ret = run_command(&cmd);
3579 /* force re-reading of the cache */
3580 if (!ret && (discard_index(r->index) < 0 ||
3581 repo_read_index(r) < 0))
3582 ret = error(_("could not read index"));
3583 goto leave_merge;
3586 merge_commit = to_merge->item;
3587 bases = get_merge_bases(head_commit, merge_commit);
3588 if (bases && oideq(&merge_commit->object.oid,
3589 &bases->item->object.oid)) {
3590 ret = 0;
3591 /* skip merging an ancestor of HEAD */
3592 goto leave_merge;
3595 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3596 git_path_merge_head(r), 0);
3597 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3599 for (j = bases; j; j = j->next)
3600 commit_list_insert(j->item, &reversed);
3601 free_commit_list(bases);
3603 repo_read_index(r);
3604 init_merge_options(&o, r);
3605 o.branch1 = "HEAD";
3606 o.branch2 = ref_name.buf;
3607 o.buffer_output = 2;
3609 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3610 if (ret <= 0)
3611 fputs(o.obuf.buf, stdout);
3612 strbuf_release(&o.obuf);
3613 if (ret < 0) {
3614 error(_("could not even attempt to merge '%.*s'"),
3615 merge_arg_len, arg);
3616 goto leave_merge;
3619 * The return value of merge_recursive() is 1 on clean, and 0 on
3620 * unclean merge.
3622 * Let's reverse that, so that do_merge() returns 0 upon success and
3623 * 1 upon failed merge (keeping the return value -1 for the cases where
3624 * we will want to reschedule the `merge` command).
3626 ret = !ret;
3628 if (r->index->cache_changed &&
3629 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3630 ret = error(_("merge: Unable to write new index file"));
3631 goto leave_merge;
3634 rollback_lock_file(&lock);
3635 if (ret)
3636 repo_rerere(r, opts->allow_rerere_auto);
3637 else
3639 * In case of problems, we now want to return a positive
3640 * value (a negative one would indicate that the `merge`
3641 * command needs to be rescheduled).
3643 fast_forward_edit:
3644 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3645 run_commit_flags);
3647 leave_merge:
3648 strbuf_release(&ref_name);
3649 rollback_lock_file(&lock);
3650 free_commit_list(to_merge);
3651 return ret;
3654 static int is_final_fixup(struct todo_list *todo_list)
3656 int i = todo_list->current;
3658 if (!is_fixup(todo_list->items[i].command))
3659 return 0;
3661 while (++i < todo_list->nr)
3662 if (is_fixup(todo_list->items[i].command))
3663 return 0;
3664 else if (!is_noop(todo_list->items[i].command))
3665 break;
3666 return 1;
3669 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3671 int i;
3673 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3674 if (!is_noop(todo_list->items[i].command))
3675 return todo_list->items[i].command;
3677 return -1;
3680 static int apply_autostash(struct replay_opts *opts)
3682 struct strbuf stash_sha1 = STRBUF_INIT;
3683 struct child_process child = CHILD_PROCESS_INIT;
3684 int ret = 0;
3686 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3687 strbuf_release(&stash_sha1);
3688 return 0;
3690 strbuf_trim(&stash_sha1);
3692 child.git_cmd = 1;
3693 child.no_stdout = 1;
3694 child.no_stderr = 1;
3695 argv_array_push(&child.args, "stash");
3696 argv_array_push(&child.args, "apply");
3697 argv_array_push(&child.args, stash_sha1.buf);
3698 if (!run_command(&child))
3699 fprintf(stderr, _("Applied autostash.\n"));
3700 else {
3701 struct child_process store = CHILD_PROCESS_INIT;
3703 store.git_cmd = 1;
3704 argv_array_push(&store.args, "stash");
3705 argv_array_push(&store.args, "store");
3706 argv_array_push(&store.args, "-m");
3707 argv_array_push(&store.args, "autostash");
3708 argv_array_push(&store.args, "-q");
3709 argv_array_push(&store.args, stash_sha1.buf);
3710 if (run_command(&store))
3711 ret = error(_("cannot store %s"), stash_sha1.buf);
3712 else
3713 fprintf(stderr,
3714 _("Applying autostash resulted in conflicts.\n"
3715 "Your changes are safe in the stash.\n"
3716 "You can run \"git stash pop\" or"
3717 " \"git stash drop\" at any time.\n"));
3720 strbuf_release(&stash_sha1);
3721 return ret;
3724 static const char *reflog_message(struct replay_opts *opts,
3725 const char *sub_action, const char *fmt, ...)
3727 va_list ap;
3728 static struct strbuf buf = STRBUF_INIT;
3729 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3731 va_start(ap, fmt);
3732 strbuf_reset(&buf);
3733 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3734 if (sub_action)
3735 strbuf_addf(&buf, " (%s)", sub_action);
3736 if (fmt) {
3737 strbuf_addstr(&buf, ": ");
3738 strbuf_vaddf(&buf, fmt, ap);
3740 va_end(ap);
3742 return buf.buf;
3745 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3746 const char *commit, const char *action)
3748 struct child_process cmd = CHILD_PROCESS_INIT;
3749 int ret;
3751 cmd.git_cmd = 1;
3753 argv_array_push(&cmd.args, "checkout");
3754 argv_array_push(&cmd.args, commit);
3755 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3757 if (opts->verbose)
3758 ret = run_command(&cmd);
3759 else
3760 ret = run_command_silent_on_success(&cmd);
3762 if (!ret)
3763 discard_index(r->index);
3765 return ret;
3768 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3769 const char *onto_name, const struct object_id *onto,
3770 const char *orig_head)
3772 struct object_id oid;
3773 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3775 if (get_oid(orig_head, &oid))
3776 return error(_("%s: not a valid OID"), orig_head);
3778 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3779 apply_autostash(opts);
3780 sequencer_remove_state(opts);
3781 return error(_("could not detach HEAD"));
3784 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3787 static int stopped_at_head(struct repository *r)
3789 struct object_id head;
3790 struct commit *commit;
3791 struct commit_message message;
3793 if (get_oid("HEAD", &head) ||
3794 !(commit = lookup_commit(r, &head)) ||
3795 parse_commit(commit) || get_message(commit, &message))
3796 fprintf(stderr, _("Stopped at HEAD\n"));
3797 else {
3798 fprintf(stderr, _("Stopped at %s\n"), message.label);
3799 free_message(commit, &message);
3801 return 0;
3805 static const char rescheduled_advice[] =
3806 N_("Could not execute the todo command\n"
3807 "\n"
3808 " %.*s"
3809 "\n"
3810 "It has been rescheduled; To edit the command before continuing, please\n"
3811 "edit the todo list first:\n"
3812 "\n"
3813 " git rebase --edit-todo\n"
3814 " git rebase --continue\n");
3816 static int pick_commits(struct repository *r,
3817 struct todo_list *todo_list,
3818 struct replay_opts *opts)
3820 int res = 0, reschedule = 0;
3821 char *prev_reflog_action;
3823 /* Note that 0 for 3rd parameter of setenv means set only if not set */
3824 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3825 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
3826 if (opts->allow_ff)
3827 assert(!(opts->signoff || opts->no_commit ||
3828 opts->record_origin || opts->edit));
3829 if (read_and_refresh_cache(r, opts))
3830 return -1;
3832 while (todo_list->current < todo_list->nr) {
3833 struct todo_item *item = todo_list->items + todo_list->current;
3834 const char *arg = todo_item_get_arg(todo_list, item);
3835 int check_todo = 0;
3837 if (save_todo(todo_list, opts))
3838 return -1;
3839 if (is_rebase_i(opts)) {
3840 if (item->command != TODO_COMMENT) {
3841 FILE *f = fopen(rebase_path_msgnum(), "w");
3843 todo_list->done_nr++;
3845 if (f) {
3846 fprintf(f, "%d\n", todo_list->done_nr);
3847 fclose(f);
3849 if (!opts->quiet)
3850 fprintf(stderr, _("Rebasing (%d/%d)%s"),
3851 todo_list->done_nr,
3852 todo_list->total_nr,
3853 opts->verbose ? "\n" : "\r");
3855 unlink(rebase_path_message());
3856 unlink(rebase_path_author_script());
3857 unlink(rebase_path_stopped_sha());
3858 unlink(rebase_path_amend());
3859 unlink(git_path_merge_head(r));
3860 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3862 if (item->command == TODO_BREAK) {
3863 if (!opts->verbose)
3864 term_clear_line();
3865 return stopped_at_head(r);
3868 if (item->command <= TODO_SQUASH) {
3869 if (is_rebase_i(opts))
3870 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
3871 command_to_string(item->command), NULL),
3873 res = do_pick_commit(r, item->command, item->commit,
3874 opts, is_final_fixup(todo_list),
3875 &check_todo);
3876 if (is_rebase_i(opts))
3877 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
3878 if (is_rebase_i(opts) && res < 0) {
3879 /* Reschedule */
3880 advise(_(rescheduled_advice),
3881 get_item_line_length(todo_list,
3882 todo_list->current),
3883 get_item_line(todo_list,
3884 todo_list->current));
3885 todo_list->current--;
3886 if (save_todo(todo_list, opts))
3887 return -1;
3889 if (item->command == TODO_EDIT) {
3890 struct commit *commit = item->commit;
3891 if (!res) {
3892 if (!opts->verbose)
3893 term_clear_line();
3894 fprintf(stderr,
3895 _("Stopped at %s... %.*s\n"),
3896 short_commit_name(commit),
3897 item->arg_len, arg);
3899 return error_with_patch(r, commit,
3900 arg, item->arg_len, opts, res, !res);
3902 if (is_rebase_i(opts) && !res)
3903 record_in_rewritten(&item->commit->object.oid,
3904 peek_command(todo_list, 1));
3905 if (res && is_fixup(item->command)) {
3906 if (res == 1)
3907 intend_to_amend();
3908 return error_failed_squash(r, item->commit, opts,
3909 item->arg_len, arg);
3910 } else if (res && is_rebase_i(opts) && item->commit) {
3911 int to_amend = 0;
3912 struct object_id oid;
3915 * If we are rewording and have either
3916 * fast-forwarded already, or are about to
3917 * create a new root commit, we want to amend,
3918 * otherwise we do not.
3920 if (item->command == TODO_REWORD &&
3921 !get_oid("HEAD", &oid) &&
3922 (oideq(&item->commit->object.oid, &oid) ||
3923 (opts->have_squash_onto &&
3924 oideq(&opts->squash_onto, &oid))))
3925 to_amend = 1;
3927 return res | error_with_patch(r, item->commit,
3928 arg, item->arg_len, opts,
3929 res, to_amend);
3931 } else if (item->command == TODO_EXEC) {
3932 char *end_of_arg = (char *)(arg + item->arg_len);
3933 int saved = *end_of_arg;
3935 if (!opts->verbose)
3936 term_clear_line();
3937 *end_of_arg = '\0';
3938 res = do_exec(r, arg);
3939 *end_of_arg = saved;
3941 if (res) {
3942 if (opts->reschedule_failed_exec)
3943 reschedule = 1;
3945 check_todo = 1;
3946 } else if (item->command == TODO_LABEL) {
3947 if ((res = do_label(r, arg, item->arg_len)))
3948 reschedule = 1;
3949 } else if (item->command == TODO_RESET) {
3950 if ((res = do_reset(r, arg, item->arg_len, opts)))
3951 reschedule = 1;
3952 } else if (item->command == TODO_MERGE) {
3953 if ((res = do_merge(r, item->commit,
3954 arg, item->arg_len,
3955 item->flags, opts)) < 0)
3956 reschedule = 1;
3957 else if (item->commit)
3958 record_in_rewritten(&item->commit->object.oid,
3959 peek_command(todo_list, 1));
3960 if (res > 0)
3961 /* failed with merge conflicts */
3962 return error_with_patch(r, item->commit,
3963 arg, item->arg_len,
3964 opts, res, 0);
3965 } else if (!is_noop(item->command))
3966 return error(_("unknown command %d"), item->command);
3968 if (reschedule) {
3969 advise(_(rescheduled_advice),
3970 get_item_line_length(todo_list,
3971 todo_list->current),
3972 get_item_line(todo_list, todo_list->current));
3973 todo_list->current--;
3974 if (save_todo(todo_list, opts))
3975 return -1;
3976 if (item->commit)
3977 return error_with_patch(r,
3978 item->commit,
3979 arg, item->arg_len,
3980 opts, res, 0);
3981 } else if (is_rebase_i(opts) && check_todo && !res) {
3982 struct stat st;
3984 if (stat(get_todo_path(opts), &st)) {
3985 res = error_errno(_("could not stat '%s'"),
3986 get_todo_path(opts));
3987 } else if (match_stat_data(&todo_list->stat, &st)) {
3988 /* Reread the todo file if it has changed. */
3989 todo_list_release(todo_list);
3990 if (read_populate_todo(r, todo_list, opts))
3991 res = -1; /* message was printed */
3992 /* `current` will be incremented below */
3993 todo_list->current = -1;
3997 todo_list->current++;
3998 if (res)
3999 return res;
4002 if (is_rebase_i(opts)) {
4003 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4004 struct stat st;
4006 /* Stopped in the middle, as planned? */
4007 if (todo_list->current < todo_list->nr)
4008 return 0;
4010 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4011 starts_with(head_ref.buf, "refs/")) {
4012 const char *msg;
4013 struct object_id head, orig;
4014 int res;
4016 if (get_oid("HEAD", &head)) {
4017 res = error(_("cannot read HEAD"));
4018 cleanup_head_ref:
4019 strbuf_release(&head_ref);
4020 strbuf_release(&buf);
4021 return res;
4023 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4024 get_oid_hex(buf.buf, &orig)) {
4025 res = error(_("could not read orig-head"));
4026 goto cleanup_head_ref;
4028 strbuf_reset(&buf);
4029 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4030 res = error(_("could not read 'onto'"));
4031 goto cleanup_head_ref;
4033 msg = reflog_message(opts, "finish", "%s onto %s",
4034 head_ref.buf, buf.buf);
4035 if (update_ref(msg, head_ref.buf, &head, &orig,
4036 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4037 res = error(_("could not update %s"),
4038 head_ref.buf);
4039 goto cleanup_head_ref;
4041 msg = reflog_message(opts, "finish", "returning to %s",
4042 head_ref.buf);
4043 if (create_symref("HEAD", head_ref.buf, msg)) {
4044 res = error(_("could not update HEAD to %s"),
4045 head_ref.buf);
4046 goto cleanup_head_ref;
4048 strbuf_reset(&buf);
4051 if (opts->verbose) {
4052 struct rev_info log_tree_opt;
4053 struct object_id orig, head;
4055 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4056 repo_init_revisions(r, &log_tree_opt, NULL);
4057 log_tree_opt.diff = 1;
4058 log_tree_opt.diffopt.output_format =
4059 DIFF_FORMAT_DIFFSTAT;
4060 log_tree_opt.disable_stdin = 1;
4062 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4063 !get_oid(buf.buf, &orig) &&
4064 !get_oid("HEAD", &head)) {
4065 diff_tree_oid(&orig, &head, "",
4066 &log_tree_opt.diffopt);
4067 log_tree_diff_flush(&log_tree_opt);
4070 flush_rewritten_pending();
4071 if (!stat(rebase_path_rewritten_list(), &st) &&
4072 st.st_size > 0) {
4073 struct child_process child = CHILD_PROCESS_INIT;
4074 const char *post_rewrite_hook =
4075 find_hook("post-rewrite");
4077 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4078 child.git_cmd = 1;
4079 argv_array_push(&child.args, "notes");
4080 argv_array_push(&child.args, "copy");
4081 argv_array_push(&child.args, "--for-rewrite=rebase");
4082 /* we don't care if this copying failed */
4083 run_command(&child);
4085 if (post_rewrite_hook) {
4086 struct child_process hook = CHILD_PROCESS_INIT;
4088 hook.in = open(rebase_path_rewritten_list(),
4089 O_RDONLY);
4090 hook.stdout_to_stderr = 1;
4091 hook.trace2_hook_name = "post-rewrite";
4092 argv_array_push(&hook.args, post_rewrite_hook);
4093 argv_array_push(&hook.args, "rebase");
4094 /* we don't care if this hook failed */
4095 run_command(&hook);
4098 apply_autostash(opts);
4100 if (!opts->quiet) {
4101 if (!opts->verbose)
4102 term_clear_line();
4103 fprintf(stderr,
4104 _("Successfully rebased and updated %s.\n"),
4105 head_ref.buf);
4108 strbuf_release(&buf);
4109 strbuf_release(&head_ref);
4113 * Sequence of picks finished successfully; cleanup by
4114 * removing the .git/sequencer directory
4116 return sequencer_remove_state(opts);
4119 static int continue_single_pick(struct repository *r)
4121 const char *argv[] = { "commit", NULL };
4123 if (!file_exists(git_path_cherry_pick_head(r)) &&
4124 !file_exists(git_path_revert_head(r)))
4125 return error(_("no cherry-pick or revert in progress"));
4126 return run_command_v_opt(argv, RUN_GIT_CMD);
4129 static int commit_staged_changes(struct repository *r,
4130 struct replay_opts *opts,
4131 struct todo_list *todo_list)
4133 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4134 unsigned int final_fixup = 0, is_clean;
4136 if (has_unstaged_changes(r, 1))
4137 return error(_("cannot rebase: You have unstaged changes."));
4139 is_clean = !has_uncommitted_changes(r, 0);
4141 if (file_exists(rebase_path_amend())) {
4142 struct strbuf rev = STRBUF_INIT;
4143 struct object_id head, to_amend;
4145 if (get_oid("HEAD", &head))
4146 return error(_("cannot amend non-existing commit"));
4147 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4148 return error(_("invalid file: '%s'"), rebase_path_amend());
4149 if (get_oid_hex(rev.buf, &to_amend))
4150 return error(_("invalid contents: '%s'"),
4151 rebase_path_amend());
4152 if (!is_clean && !oideq(&head, &to_amend))
4153 return error(_("\nYou have uncommitted changes in your "
4154 "working tree. Please, commit them\n"
4155 "first and then run 'git rebase "
4156 "--continue' again."));
4158 * When skipping a failed fixup/squash, we need to edit the
4159 * commit message, the current fixup list and count, and if it
4160 * was the last fixup/squash in the chain, we need to clean up
4161 * the commit message and if there was a squash, let the user
4162 * edit it.
4164 if (!is_clean || !opts->current_fixup_count)
4165 ; /* this is not the final fixup */
4166 else if (!oideq(&head, &to_amend) ||
4167 !file_exists(rebase_path_stopped_sha())) {
4168 /* was a final fixup or squash done manually? */
4169 if (!is_fixup(peek_command(todo_list, 0))) {
4170 unlink(rebase_path_fixup_msg());
4171 unlink(rebase_path_squash_msg());
4172 unlink(rebase_path_current_fixups());
4173 strbuf_reset(&opts->current_fixups);
4174 opts->current_fixup_count = 0;
4176 } else {
4177 /* we are in a fixup/squash chain */
4178 const char *p = opts->current_fixups.buf;
4179 int len = opts->current_fixups.len;
4181 opts->current_fixup_count--;
4182 if (!len)
4183 BUG("Incorrect current_fixups:\n%s", p);
4184 while (len && p[len - 1] != '\n')
4185 len--;
4186 strbuf_setlen(&opts->current_fixups, len);
4187 if (write_message(p, len, rebase_path_current_fixups(),
4188 0) < 0)
4189 return error(_("could not write file: '%s'"),
4190 rebase_path_current_fixups());
4193 * If a fixup/squash in a fixup/squash chain failed, the
4194 * commit message is already correct, no need to commit
4195 * it again.
4197 * Only if it is the final command in the fixup/squash
4198 * chain, and only if the chain is longer than a single
4199 * fixup/squash command (which was just skipped), do we
4200 * actually need to re-commit with a cleaned up commit
4201 * message.
4203 if (opts->current_fixup_count > 0 &&
4204 !is_fixup(peek_command(todo_list, 0))) {
4205 final_fixup = 1;
4207 * If there was not a single "squash" in the
4208 * chain, we only need to clean up the commit
4209 * message, no need to bother the user with
4210 * opening the commit message in the editor.
4212 if (!starts_with(p, "squash ") &&
4213 !strstr(p, "\nsquash "))
4214 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4215 } else if (is_fixup(peek_command(todo_list, 0))) {
4217 * We need to update the squash message to skip
4218 * the latest commit message.
4220 struct commit *commit;
4221 const char *path = rebase_path_squash_msg();
4222 const char *encoding = get_commit_output_encoding();
4224 if (parse_head(r, &commit) ||
4225 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4226 write_message(p, strlen(p), path, 0)) {
4227 unuse_commit_buffer(commit, p);
4228 return error(_("could not write file: "
4229 "'%s'"), path);
4231 unuse_commit_buffer(commit, p);
4235 strbuf_release(&rev);
4236 flags |= AMEND_MSG;
4239 if (is_clean) {
4240 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4242 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4243 return error(_("could not remove CHERRY_PICK_HEAD"));
4244 if (!final_fixup)
4245 return 0;
4248 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4249 opts, flags))
4250 return error(_("could not commit staged changes."));
4251 unlink(rebase_path_amend());
4252 unlink(git_path_merge_head(r));
4253 if (final_fixup) {
4254 unlink(rebase_path_fixup_msg());
4255 unlink(rebase_path_squash_msg());
4257 if (opts->current_fixup_count > 0) {
4259 * Whether final fixup or not, we just cleaned up the commit
4260 * message...
4262 unlink(rebase_path_current_fixups());
4263 strbuf_reset(&opts->current_fixups);
4264 opts->current_fixup_count = 0;
4266 return 0;
4269 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4271 struct todo_list todo_list = TODO_LIST_INIT;
4272 int res;
4274 if (read_and_refresh_cache(r, opts))
4275 return -1;
4277 if (read_populate_opts(opts))
4278 return -1;
4279 if (is_rebase_i(opts)) {
4280 if ((res = read_populate_todo(r, &todo_list, opts)))
4281 goto release_todo_list;
4283 if (file_exists(rebase_path_dropped())) {
4284 if ((res = todo_list_check_against_backup(r, &todo_list)))
4285 goto release_todo_list;
4287 unlink(rebase_path_dropped());
4290 if (commit_staged_changes(r, opts, &todo_list)) {
4291 res = -1;
4292 goto release_todo_list;
4294 } else if (!file_exists(get_todo_path(opts)))
4295 return continue_single_pick(r);
4296 else if ((res = read_populate_todo(r, &todo_list, opts)))
4297 goto release_todo_list;
4299 if (!is_rebase_i(opts)) {
4300 /* Verify that the conflict has been resolved */
4301 if (file_exists(git_path_cherry_pick_head(r)) ||
4302 file_exists(git_path_revert_head(r))) {
4303 res = continue_single_pick(r);
4304 if (res)
4305 goto release_todo_list;
4307 if (index_differs_from(r, "HEAD", NULL, 0)) {
4308 res = error_dirty_index(r, opts);
4309 goto release_todo_list;
4311 todo_list.current++;
4312 } else if (file_exists(rebase_path_stopped_sha())) {
4313 struct strbuf buf = STRBUF_INIT;
4314 struct object_id oid;
4316 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4317 !get_oid_committish(buf.buf, &oid))
4318 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4319 strbuf_release(&buf);
4322 res = pick_commits(r, &todo_list, opts);
4323 release_todo_list:
4324 todo_list_release(&todo_list);
4325 return res;
4328 static int single_pick(struct repository *r,
4329 struct commit *cmit,
4330 struct replay_opts *opts)
4332 int check_todo;
4334 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4335 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4336 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4337 &check_todo);
4340 int sequencer_pick_revisions(struct repository *r,
4341 struct replay_opts *opts)
4343 struct todo_list todo_list = TODO_LIST_INIT;
4344 struct object_id oid;
4345 int i, res;
4347 assert(opts->revs);
4348 if (read_and_refresh_cache(r, opts))
4349 return -1;
4351 for (i = 0; i < opts->revs->pending.nr; i++) {
4352 struct object_id oid;
4353 const char *name = opts->revs->pending.objects[i].name;
4355 /* This happens when using --stdin. */
4356 if (!strlen(name))
4357 continue;
4359 if (!get_oid(name, &oid)) {
4360 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4361 enum object_type type = oid_object_info(r,
4362 &oid,
4363 NULL);
4364 return error(_("%s: can't cherry-pick a %s"),
4365 name, type_name(type));
4367 } else
4368 return error(_("%s: bad revision"), name);
4372 * If we were called as "git cherry-pick <commit>", just
4373 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4374 * REVERT_HEAD, and don't touch the sequencer state.
4375 * This means it is possible to cherry-pick in the middle
4376 * of a cherry-pick sequence.
4378 if (opts->revs->cmdline.nr == 1 &&
4379 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4380 opts->revs->no_walk &&
4381 !opts->revs->cmdline.rev->flags) {
4382 struct commit *cmit;
4383 if (prepare_revision_walk(opts->revs))
4384 return error(_("revision walk setup failed"));
4385 cmit = get_revision(opts->revs);
4386 if (!cmit)
4387 return error(_("empty commit set passed"));
4388 if (get_revision(opts->revs))
4389 BUG("unexpected extra commit from walk");
4390 return single_pick(r, cmit, opts);
4394 * Start a new cherry-pick/ revert sequence; but
4395 * first, make sure that an existing one isn't in
4396 * progress
4399 if (walk_revs_populate_todo(&todo_list, opts) ||
4400 create_seq_dir(r) < 0)
4401 return -1;
4402 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4403 return error(_("can't revert as initial commit"));
4404 if (save_head(oid_to_hex(&oid)))
4405 return -1;
4406 if (save_opts(opts))
4407 return -1;
4408 update_abort_safety_file();
4409 res = pick_commits(r, &todo_list, opts);
4410 todo_list_release(&todo_list);
4411 return res;
4414 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4416 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4417 struct strbuf sob = STRBUF_INIT;
4418 int has_footer;
4420 strbuf_addstr(&sob, sign_off_header);
4421 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4422 strbuf_addch(&sob, '\n');
4424 if (!ignore_footer)
4425 strbuf_complete_line(msgbuf);
4428 * If the whole message buffer is equal to the sob, pretend that we
4429 * found a conforming footer with a matching sob
4431 if (msgbuf->len - ignore_footer == sob.len &&
4432 !strncmp(msgbuf->buf, sob.buf, sob.len))
4433 has_footer = 3;
4434 else
4435 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4437 if (!has_footer) {
4438 const char *append_newlines = NULL;
4439 size_t len = msgbuf->len - ignore_footer;
4441 if (!len) {
4443 * The buffer is completely empty. Leave foom for
4444 * the title and body to be filled in by the user.
4446 append_newlines = "\n\n";
4447 } else if (len == 1) {
4449 * Buffer contains a single newline. Add another
4450 * so that we leave room for the title and body.
4452 append_newlines = "\n";
4453 } else if (msgbuf->buf[len - 2] != '\n') {
4455 * Buffer ends with a single newline. Add another
4456 * so that there is an empty line between the message
4457 * body and the sob.
4459 append_newlines = "\n";
4460 } /* else, the buffer already ends with two newlines. */
4462 if (append_newlines)
4463 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4464 append_newlines, strlen(append_newlines));
4467 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4468 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4469 sob.buf, sob.len);
4471 strbuf_release(&sob);
4474 struct labels_entry {
4475 struct hashmap_entry entry;
4476 char label[FLEX_ARRAY];
4479 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4480 const struct hashmap_entry *entry_or_key, const void *key)
4482 const struct labels_entry *a, *b;
4484 a = container_of(eptr, const struct labels_entry, entry);
4485 b = container_of(entry_or_key, const struct labels_entry, entry);
4487 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4490 struct string_entry {
4491 struct oidmap_entry entry;
4492 char string[FLEX_ARRAY];
4495 struct label_state {
4496 struct oidmap commit2label;
4497 struct hashmap labels;
4498 struct strbuf buf;
4501 static const char *label_oid(struct object_id *oid, const char *label,
4502 struct label_state *state)
4504 struct labels_entry *labels_entry;
4505 struct string_entry *string_entry;
4506 struct object_id dummy;
4507 int i;
4509 string_entry = oidmap_get(&state->commit2label, oid);
4510 if (string_entry)
4511 return string_entry->string;
4514 * For "uninteresting" commits, i.e. commits that are not to be
4515 * rebased, and which can therefore not be labeled, we use a unique
4516 * abbreviation of the commit name. This is slightly more complicated
4517 * than calling find_unique_abbrev() because we also need to make
4518 * sure that the abbreviation does not conflict with any other
4519 * label.
4521 * We disallow "interesting" commits to be labeled by a string that
4522 * is a valid full-length hash, to ensure that we always can find an
4523 * abbreviation for any uninteresting commit's names that does not
4524 * clash with any other label.
4526 strbuf_reset(&state->buf);
4527 if (!label) {
4528 char *p;
4530 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4531 label = p = state->buf.buf;
4533 find_unique_abbrev_r(p, oid, default_abbrev);
4536 * We may need to extend the abbreviated hash so that there is
4537 * no conflicting label.
4539 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4540 size_t i = strlen(p) + 1;
4542 oid_to_hex_r(p, oid);
4543 for (; i < the_hash_algo->hexsz; i++) {
4544 char save = p[i];
4545 p[i] = '\0';
4546 if (!hashmap_get_from_hash(&state->labels,
4547 strihash(p), p))
4548 break;
4549 p[i] = save;
4552 } else {
4553 struct strbuf *buf = &state->buf;
4556 * Sanitize labels by replacing non-alpha-numeric characters
4557 * (including white-space ones) by dashes, as they might be
4558 * illegal in file names (and hence in ref names).
4560 * Note that we retain non-ASCII UTF-8 characters (identified
4561 * via the most significant bit). They should be all acceptable
4562 * in file names. We do not validate the UTF-8 here, that's not
4563 * the job of this function.
4565 for (; *label; label++)
4566 if ((*label & 0x80) || isalnum(*label))
4567 strbuf_addch(buf, *label);
4568 /* avoid leading dash and double-dashes */
4569 else if (buf->len && buf->buf[buf->len - 1] != '-')
4570 strbuf_addch(buf, '-');
4571 if (!buf->len) {
4572 strbuf_addstr(buf, "rev-");
4573 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4575 label = buf->buf;
4577 if ((buf->len == the_hash_algo->hexsz &&
4578 !get_oid_hex(label, &dummy)) ||
4579 (buf->len == 1 && *label == '#') ||
4580 hashmap_get_from_hash(&state->labels,
4581 strihash(label), label)) {
4583 * If the label already exists, or if the label is a
4584 * valid full OID, or the label is a '#' (which we use
4585 * as a separator between merge heads and oneline), we
4586 * append a dash and a number to make it unique.
4588 size_t len = buf->len;
4590 for (i = 2; ; i++) {
4591 strbuf_setlen(buf, len);
4592 strbuf_addf(buf, "-%d", i);
4593 if (!hashmap_get_from_hash(&state->labels,
4594 strihash(buf->buf),
4595 buf->buf))
4596 break;
4599 label = buf->buf;
4603 FLEX_ALLOC_STR(labels_entry, label, label);
4604 hashmap_entry_init(&labels_entry->entry, strihash(label));
4605 hashmap_add(&state->labels, &labels_entry->entry);
4607 FLEX_ALLOC_STR(string_entry, string, label);
4608 oidcpy(&string_entry->entry.oid, oid);
4609 oidmap_put(&state->commit2label, string_entry);
4611 return string_entry->string;
4614 static int make_script_with_merges(struct pretty_print_context *pp,
4615 struct rev_info *revs, struct strbuf *out,
4616 unsigned flags)
4618 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4619 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4620 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4621 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4622 struct strbuf label = STRBUF_INIT;
4623 struct commit_list *commits = NULL, **tail = &commits, *iter;
4624 struct commit_list *tips = NULL, **tips_tail = &tips;
4625 struct commit *commit;
4626 struct oidmap commit2todo = OIDMAP_INIT;
4627 struct string_entry *entry;
4628 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4629 shown = OIDSET_INIT;
4630 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4632 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4633 const char *cmd_pick = abbr ? "p" : "pick",
4634 *cmd_label = abbr ? "l" : "label",
4635 *cmd_reset = abbr ? "t" : "reset",
4636 *cmd_merge = abbr ? "m" : "merge";
4638 oidmap_init(&commit2todo, 0);
4639 oidmap_init(&state.commit2label, 0);
4640 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4641 strbuf_init(&state.buf, 32);
4643 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4644 struct labels_entry *onto_label_entry;
4645 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4646 FLEX_ALLOC_STR(entry, string, "onto");
4647 oidcpy(&entry->entry.oid, oid);
4648 oidmap_put(&state.commit2label, entry);
4650 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4651 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4652 hashmap_add(&state.labels, &onto_label_entry->entry);
4656 * First phase:
4657 * - get onelines for all commits
4658 * - gather all branch tips (i.e. 2nd or later parents of merges)
4659 * - label all branch tips
4661 while ((commit = get_revision(revs))) {
4662 struct commit_list *to_merge;
4663 const char *p1, *p2;
4664 struct object_id *oid;
4665 int is_empty;
4667 tail = &commit_list_insert(commit, tail)->next;
4668 oidset_insert(&interesting, &commit->object.oid);
4670 is_empty = is_original_commit_empty(commit);
4671 if (!is_empty && (commit->object.flags & PATCHSAME))
4672 continue;
4673 if (is_empty && !keep_empty)
4674 continue;
4676 strbuf_reset(&oneline);
4677 pretty_print_commit(pp, commit, &oneline);
4679 to_merge = commit->parents ? commit->parents->next : NULL;
4680 if (!to_merge) {
4681 /* non-merge commit: easy case */
4682 strbuf_reset(&buf);
4683 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4684 oid_to_hex(&commit->object.oid),
4685 oneline.buf);
4686 if (is_empty)
4687 strbuf_addf(&buf, " %c empty",
4688 comment_line_char);
4690 FLEX_ALLOC_STR(entry, string, buf.buf);
4691 oidcpy(&entry->entry.oid, &commit->object.oid);
4692 oidmap_put(&commit2todo, entry);
4694 continue;
4697 /* Create a label */
4698 strbuf_reset(&label);
4699 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4700 (p1 = strchr(p1, '\'')) &&
4701 (p2 = strchr(++p1, '\'')))
4702 strbuf_add(&label, p1, p2 - p1);
4703 else if (skip_prefix(oneline.buf, "Merge pull request ",
4704 &p1) &&
4705 (p1 = strstr(p1, " from ")))
4706 strbuf_addstr(&label, p1 + strlen(" from "));
4707 else
4708 strbuf_addbuf(&label, &oneline);
4710 strbuf_reset(&buf);
4711 strbuf_addf(&buf, "%s -C %s",
4712 cmd_merge, oid_to_hex(&commit->object.oid));
4714 /* label the tips of merged branches */
4715 for (; to_merge; to_merge = to_merge->next) {
4716 oid = &to_merge->item->object.oid;
4717 strbuf_addch(&buf, ' ');
4719 if (!oidset_contains(&interesting, oid)) {
4720 strbuf_addstr(&buf, label_oid(oid, NULL,
4721 &state));
4722 continue;
4725 tips_tail = &commit_list_insert(to_merge->item,
4726 tips_tail)->next;
4728 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4730 strbuf_addf(&buf, " # %s", oneline.buf);
4732 FLEX_ALLOC_STR(entry, string, buf.buf);
4733 oidcpy(&entry->entry.oid, &commit->object.oid);
4734 oidmap_put(&commit2todo, entry);
4738 * Second phase:
4739 * - label branch points
4740 * - add HEAD to the branch tips
4742 for (iter = commits; iter; iter = iter->next) {
4743 struct commit_list *parent = iter->item->parents;
4744 for (; parent; parent = parent->next) {
4745 struct object_id *oid = &parent->item->object.oid;
4746 if (!oidset_contains(&interesting, oid))
4747 continue;
4748 if (oidset_insert(&child_seen, oid))
4749 label_oid(oid, "branch-point", &state);
4752 /* Add HEAD as implicit "tip of branch" */
4753 if (!iter->next)
4754 tips_tail = &commit_list_insert(iter->item,
4755 tips_tail)->next;
4759 * Third phase: output the todo list. This is a bit tricky, as we
4760 * want to avoid jumping back and forth between revisions. To
4761 * accomplish that goal, we walk backwards from the branch tips,
4762 * gathering commits not yet shown, reversing the list on the fly,
4763 * then outputting that list (labeling revisions as needed).
4765 strbuf_addf(out, "%s onto\n", cmd_label);
4766 for (iter = tips; iter; iter = iter->next) {
4767 struct commit_list *list = NULL, *iter2;
4769 commit = iter->item;
4770 if (oidset_contains(&shown, &commit->object.oid))
4771 continue;
4772 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4774 if (entry)
4775 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4776 else
4777 strbuf_addch(out, '\n');
4779 while (oidset_contains(&interesting, &commit->object.oid) &&
4780 !oidset_contains(&shown, &commit->object.oid)) {
4781 commit_list_insert(commit, &list);
4782 if (!commit->parents) {
4783 commit = NULL;
4784 break;
4786 commit = commit->parents->item;
4789 if (!commit)
4790 strbuf_addf(out, "%s %s\n", cmd_reset,
4791 rebase_cousins || root_with_onto ?
4792 "onto" : "[new root]");
4793 else {
4794 const char *to = NULL;
4796 entry = oidmap_get(&state.commit2label,
4797 &commit->object.oid);
4798 if (entry)
4799 to = entry->string;
4800 else if (!rebase_cousins)
4801 to = label_oid(&commit->object.oid, NULL,
4802 &state);
4804 if (!to || !strcmp(to, "onto"))
4805 strbuf_addf(out, "%s onto\n", cmd_reset);
4806 else {
4807 strbuf_reset(&oneline);
4808 pretty_print_commit(pp, commit, &oneline);
4809 strbuf_addf(out, "%s %s # %s\n",
4810 cmd_reset, to, oneline.buf);
4814 for (iter2 = list; iter2; iter2 = iter2->next) {
4815 struct object_id *oid = &iter2->item->object.oid;
4816 entry = oidmap_get(&commit2todo, oid);
4817 /* only show if not already upstream */
4818 if (entry)
4819 strbuf_addf(out, "%s\n", entry->string);
4820 entry = oidmap_get(&state.commit2label, oid);
4821 if (entry)
4822 strbuf_addf(out, "%s %s\n",
4823 cmd_label, entry->string);
4824 oidset_insert(&shown, oid);
4827 free_commit_list(list);
4830 free_commit_list(commits);
4831 free_commit_list(tips);
4833 strbuf_release(&label);
4834 strbuf_release(&oneline);
4835 strbuf_release(&buf);
4837 oidmap_free(&commit2todo, 1);
4838 oidmap_free(&state.commit2label, 1);
4839 hashmap_free_entries(&state.labels, struct labels_entry, entry);
4840 strbuf_release(&state.buf);
4842 return 0;
4845 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4846 const char **argv, unsigned flags)
4848 char *format = NULL;
4849 struct pretty_print_context pp = {0};
4850 struct rev_info revs;
4851 struct commit *commit;
4852 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4853 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4854 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4855 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
4857 repo_init_revisions(r, &revs, NULL);
4858 revs.verbose_header = 1;
4859 if (!rebase_merges)
4860 revs.max_parents = 1;
4861 revs.cherry_mark = !reapply_cherry_picks;
4862 revs.limited = 1;
4863 revs.reverse = 1;
4864 revs.right_only = 1;
4865 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4866 revs.topo_order = 1;
4868 revs.pretty_given = 1;
4869 git_config_get_string("rebase.instructionFormat", &format);
4870 if (!format || !*format) {
4871 free(format);
4872 format = xstrdup("%s");
4874 get_commit_format(format, &revs);
4875 free(format);
4876 pp.fmt = revs.commit_format;
4877 pp.output_encoding = get_log_output_encoding();
4879 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4880 return error(_("make_script: unhandled options"));
4882 if (prepare_revision_walk(&revs) < 0)
4883 return error(_("make_script: error preparing revisions"));
4885 if (rebase_merges)
4886 return make_script_with_merges(&pp, &revs, out, flags);
4888 while ((commit = get_revision(&revs))) {
4889 int is_empty = is_original_commit_empty(commit);
4891 if (!is_empty && (commit->object.flags & PATCHSAME))
4892 continue;
4893 if (is_empty && !keep_empty)
4894 continue;
4895 strbuf_addf(out, "%s %s ", insn,
4896 oid_to_hex(&commit->object.oid));
4897 pretty_print_commit(&pp, commit, out);
4898 if (is_empty)
4899 strbuf_addf(out, " %c empty", comment_line_char);
4900 strbuf_addch(out, '\n');
4902 return 0;
4906 * Add commands after pick and (series of) squash/fixup commands
4907 * in the todo list.
4909 void todo_list_add_exec_commands(struct todo_list *todo_list,
4910 struct string_list *commands)
4912 struct strbuf *buf = &todo_list->buf;
4913 size_t base_offset = buf->len;
4914 int i, insert, nr = 0, alloc = 0;
4915 struct todo_item *items = NULL, *base_items = NULL;
4917 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4918 for (i = 0; i < commands->nr; i++) {
4919 size_t command_len = strlen(commands->items[i].string);
4921 strbuf_addstr(buf, commands->items[i].string);
4922 strbuf_addch(buf, '\n');
4924 base_items[i].command = TODO_EXEC;
4925 base_items[i].offset_in_buf = base_offset;
4926 base_items[i].arg_offset = base_offset + strlen("exec ");
4927 base_items[i].arg_len = command_len - strlen("exec ");
4929 base_offset += command_len + 1;
4933 * Insert <commands> after every pick. Here, fixup/squash chains
4934 * are considered part of the pick, so we insert the commands *after*
4935 * those chains if there are any.
4937 * As we insert the exec commands immediately after rearranging
4938 * any fixups and before the user edits the list, a fixup chain
4939 * can never contain comments (any comments are empty picks that
4940 * have been commented out because the user did not specify
4941 * --keep-empty). So, it is safe to insert an exec command
4942 * without looking at the command following a comment.
4944 insert = 0;
4945 for (i = 0; i < todo_list->nr; i++) {
4946 enum todo_command command = todo_list->items[i].command;
4947 if (insert && !is_fixup(command)) {
4948 ALLOC_GROW(items, nr + commands->nr, alloc);
4949 COPY_ARRAY(items + nr, base_items, commands->nr);
4950 nr += commands->nr;
4952 insert = 0;
4955 ALLOC_GROW(items, nr + 1, alloc);
4956 items[nr++] = todo_list->items[i];
4958 if (command == TODO_PICK || command == TODO_MERGE)
4959 insert = 1;
4962 /* insert or append final <commands> */
4963 if (insert || nr == todo_list->nr) {
4964 ALLOC_GROW(items, nr + commands->nr, alloc);
4965 COPY_ARRAY(items + nr, base_items, commands->nr);
4966 nr += commands->nr;
4969 free(base_items);
4970 FREE_AND_NULL(todo_list->items);
4971 todo_list->items = items;
4972 todo_list->nr = nr;
4973 todo_list->alloc = alloc;
4976 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4977 struct strbuf *buf, int num, unsigned flags)
4979 struct todo_item *item;
4980 int i, max = todo_list->nr;
4982 if (num > 0 && num < max)
4983 max = num;
4985 for (item = todo_list->items, i = 0; i < max; i++, item++) {
4986 char cmd;
4988 /* if the item is not a command write it and continue */
4989 if (item->command >= TODO_COMMENT) {
4990 strbuf_addf(buf, "%.*s\n", item->arg_len,
4991 todo_item_get_arg(todo_list, item));
4992 continue;
4995 /* add command to the buffer */
4996 cmd = command_to_char(item->command);
4997 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
4998 strbuf_addch(buf, cmd);
4999 else
5000 strbuf_addstr(buf, command_to_string(item->command));
5002 /* add commit id */
5003 if (item->commit) {
5004 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5005 short_commit_name(item->commit) :
5006 oid_to_hex(&item->commit->object.oid);
5008 if (item->command == TODO_MERGE) {
5009 if (item->flags & TODO_EDIT_MERGE_MSG)
5010 strbuf_addstr(buf, " -c");
5011 else
5012 strbuf_addstr(buf, " -C");
5015 strbuf_addf(buf, " %s", oid);
5018 /* add all the rest */
5019 if (!item->arg_len)
5020 strbuf_addch(buf, '\n');
5021 else
5022 strbuf_addf(buf, " %.*s\n", item->arg_len,
5023 todo_item_get_arg(todo_list, item));
5027 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5028 const char *file, const char *shortrevisions,
5029 const char *shortonto, int num, unsigned flags)
5031 int res;
5032 struct strbuf buf = STRBUF_INIT;
5034 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5035 if (flags & TODO_LIST_APPEND_TODO_HELP)
5036 append_todo_help(count_commands(todo_list),
5037 shortrevisions, shortonto, &buf);
5039 res = write_message(buf.buf, buf.len, file, 0);
5040 strbuf_release(&buf);
5042 return res;
5045 /* skip picking commits whose parents are unchanged */
5046 static int skip_unnecessary_picks(struct repository *r,
5047 struct todo_list *todo_list,
5048 struct object_id *base_oid)
5050 struct object_id *parent_oid;
5051 int i;
5053 for (i = 0; i < todo_list->nr; i++) {
5054 struct todo_item *item = todo_list->items + i;
5056 if (item->command >= TODO_NOOP)
5057 continue;
5058 if (item->command != TODO_PICK)
5059 break;
5060 if (parse_commit(item->commit)) {
5061 return error(_("could not parse commit '%s'"),
5062 oid_to_hex(&item->commit->object.oid));
5064 if (!item->commit->parents)
5065 break; /* root commit */
5066 if (item->commit->parents->next)
5067 break; /* merge commit */
5068 parent_oid = &item->commit->parents->item->object.oid;
5069 if (!oideq(parent_oid, base_oid))
5070 break;
5071 oidcpy(base_oid, &item->commit->object.oid);
5073 if (i > 0) {
5074 const char *done_path = rebase_path_done();
5076 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5077 error_errno(_("could not write to '%s'"), done_path);
5078 return -1;
5081 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5082 todo_list->nr -= i;
5083 todo_list->current = 0;
5084 todo_list->done_nr += i;
5086 if (is_fixup(peek_command(todo_list, 0)))
5087 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5090 return 0;
5093 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5094 const char *shortrevisions, const char *onto_name,
5095 struct commit *onto, const char *orig_head,
5096 struct string_list *commands, unsigned autosquash,
5097 struct todo_list *todo_list)
5099 const char *shortonto, *todo_file = rebase_path_todo();
5100 struct todo_list new_todo = TODO_LIST_INIT;
5101 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5102 struct object_id oid = onto->object.oid;
5103 int res;
5105 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5107 if (buf->len == 0) {
5108 struct todo_item *item = append_new_todo(todo_list);
5109 item->command = TODO_NOOP;
5110 item->commit = NULL;
5111 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5114 if (autosquash && todo_list_rearrange_squash(todo_list))
5115 return -1;
5117 if (commands->nr)
5118 todo_list_add_exec_commands(todo_list, commands);
5120 if (count_commands(todo_list) == 0) {
5121 apply_autostash(opts);
5122 sequencer_remove_state(opts);
5124 return error(_("nothing to do"));
5127 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5128 shortonto, flags);
5129 if (res == -1)
5130 return -1;
5131 else if (res == -2) {
5132 apply_autostash(opts);
5133 sequencer_remove_state(opts);
5135 return -1;
5136 } else if (res == -3) {
5137 apply_autostash(opts);
5138 sequencer_remove_state(opts);
5139 todo_list_release(&new_todo);
5141 return error(_("nothing to do"));
5142 } else if (res == -4) {
5143 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5144 todo_list_release(&new_todo);
5146 return -1;
5149 /* Expand the commit IDs */
5150 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5151 strbuf_swap(&new_todo.buf, &buf2);
5152 strbuf_release(&buf2);
5153 new_todo.total_nr -= new_todo.nr;
5154 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5155 BUG("invalid todo list after expanding IDs:\n%s",
5156 new_todo.buf.buf);
5158 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5159 todo_list_release(&new_todo);
5160 return error(_("could not skip unnecessary pick commands"));
5163 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5164 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5165 todo_list_release(&new_todo);
5166 return error_errno(_("could not write '%s'"), todo_file);
5169 res = -1;
5171 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5172 goto cleanup;
5174 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5175 goto cleanup;
5177 todo_list_write_total_nr(&new_todo);
5178 res = pick_commits(r, &new_todo, opts);
5180 cleanup:
5181 todo_list_release(&new_todo);
5183 return res;
5186 struct subject2item_entry {
5187 struct hashmap_entry entry;
5188 int i;
5189 char subject[FLEX_ARRAY];
5192 static int subject2item_cmp(const void *fndata,
5193 const struct hashmap_entry *eptr,
5194 const struct hashmap_entry *entry_or_key,
5195 const void *key)
5197 const struct subject2item_entry *a, *b;
5199 a = container_of(eptr, const struct subject2item_entry, entry);
5200 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5202 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5205 define_commit_slab(commit_todo_item, struct todo_item *);
5208 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5209 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5210 * after the former, and change "pick" to "fixup"/"squash".
5212 * Note that if the config has specified a custom instruction format, each log
5213 * message will have to be retrieved from the commit (as the oneline in the
5214 * script cannot be trusted) in order to normalize the autosquash arrangement.
5216 int todo_list_rearrange_squash(struct todo_list *todo_list)
5218 struct hashmap subject2item;
5219 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5220 char **subjects;
5221 struct commit_todo_item commit_todo;
5222 struct todo_item *items = NULL;
5224 init_commit_todo_item(&commit_todo);
5226 * The hashmap maps onelines to the respective todo list index.
5228 * If any items need to be rearranged, the next[i] value will indicate
5229 * which item was moved directly after the i'th.
5231 * In that case, last[i] will indicate the index of the latest item to
5232 * be moved to appear after the i'th.
5234 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5235 ALLOC_ARRAY(next, todo_list->nr);
5236 ALLOC_ARRAY(tail, todo_list->nr);
5237 ALLOC_ARRAY(subjects, todo_list->nr);
5238 for (i = 0; i < todo_list->nr; i++) {
5239 struct strbuf buf = STRBUF_INIT;
5240 struct todo_item *item = todo_list->items + i;
5241 const char *commit_buffer, *subject, *p;
5242 size_t subject_len;
5243 int i2 = -1;
5244 struct subject2item_entry *entry;
5246 next[i] = tail[i] = -1;
5247 if (!item->commit || item->command == TODO_DROP) {
5248 subjects[i] = NULL;
5249 continue;
5252 if (is_fixup(item->command)) {
5253 clear_commit_todo_item(&commit_todo);
5254 return error(_("the script was already rearranged."));
5257 *commit_todo_item_at(&commit_todo, item->commit) = item;
5259 parse_commit(item->commit);
5260 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5261 find_commit_subject(commit_buffer, &subject);
5262 format_subject(&buf, subject, " ");
5263 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5264 unuse_commit_buffer(item->commit, commit_buffer);
5265 if ((skip_prefix(subject, "fixup! ", &p) ||
5266 skip_prefix(subject, "squash! ", &p))) {
5267 struct commit *commit2;
5269 for (;;) {
5270 while (isspace(*p))
5271 p++;
5272 if (!skip_prefix(p, "fixup! ", &p) &&
5273 !skip_prefix(p, "squash! ", &p))
5274 break;
5277 entry = hashmap_get_entry_from_hash(&subject2item,
5278 strhash(p), p,
5279 struct subject2item_entry,
5280 entry);
5281 if (entry)
5282 /* found by title */
5283 i2 = entry->i;
5284 else if (!strchr(p, ' ') &&
5285 (commit2 =
5286 lookup_commit_reference_by_name(p)) &&
5287 *commit_todo_item_at(&commit_todo, commit2))
5288 /* found by commit name */
5289 i2 = *commit_todo_item_at(&commit_todo, commit2)
5290 - todo_list->items;
5291 else {
5292 /* copy can be a prefix of the commit subject */
5293 for (i2 = 0; i2 < i; i2++)
5294 if (subjects[i2] &&
5295 starts_with(subjects[i2], p))
5296 break;
5297 if (i2 == i)
5298 i2 = -1;
5301 if (i2 >= 0) {
5302 rearranged = 1;
5303 todo_list->items[i].command =
5304 starts_with(subject, "fixup!") ?
5305 TODO_FIXUP : TODO_SQUASH;
5306 if (next[i2] < 0)
5307 next[i2] = i;
5308 else
5309 next[tail[i2]] = i;
5310 tail[i2] = i;
5311 } else if (!hashmap_get_from_hash(&subject2item,
5312 strhash(subject), subject)) {
5313 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5314 entry->i = i;
5315 hashmap_entry_init(&entry->entry,
5316 strhash(entry->subject));
5317 hashmap_put(&subject2item, &entry->entry);
5321 if (rearranged) {
5322 for (i = 0; i < todo_list->nr; i++) {
5323 enum todo_command command = todo_list->items[i].command;
5324 int cur = i;
5327 * Initially, all commands are 'pick's. If it is a
5328 * fixup or a squash now, we have rearranged it.
5330 if (is_fixup(command))
5331 continue;
5333 while (cur >= 0) {
5334 ALLOC_GROW(items, nr + 1, alloc);
5335 items[nr++] = todo_list->items[cur];
5336 cur = next[cur];
5340 FREE_AND_NULL(todo_list->items);
5341 todo_list->items = items;
5342 todo_list->nr = nr;
5343 todo_list->alloc = alloc;
5346 free(next);
5347 free(tail);
5348 for (i = 0; i < todo_list->nr; i++)
5349 free(subjects[i]);
5350 free(subjects);
5351 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5353 clear_commit_todo_item(&commit_todo);
5355 return 0;
5358 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5360 if (file_exists(git_path_cherry_pick_head(r))) {
5361 struct object_id cherry_pick_head, rebase_head;
5363 if (file_exists(git_path_seq_dir()))
5364 *whence = FROM_CHERRY_PICK_MULTI;
5365 if (file_exists(rebase_path()) &&
5366 !get_oid("REBASE_HEAD", &rebase_head) &&
5367 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5368 oideq(&rebase_head, &cherry_pick_head))
5369 *whence = FROM_REBASE_PICK;
5370 else
5371 *whence = FROM_CHERRY_PICK_SINGLE;
5373 return 1;
5376 return 0;