Merge branch 'da/difftool-dir-diff-symlink-fix' into maint
[git.git] / sequencer.c
blobe4627d91967e3b27c60a71ff1da61b5b3025c025
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "exec-cmd.h"
12 #include "utf8.h"
13 #include "cache-tree.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "rerere.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
19 #include "refs.h"
20 #include "strvec.h"
21 #include "quote.h"
22 #include "trailer.h"
23 #include "log-tree.h"
24 #include "wt-status.h"
25 #include "hashmap.h"
26 #include "notes-utils.h"
27 #include "sigchain.h"
28 #include "unpack-trees.h"
29 #include "worktree.h"
30 #include "oidmap.h"
31 #include "oidset.h"
32 #include "commit-slab.h"
33 #include "alias.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
36 #include "reset.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
67 * actions.
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
72 * for the prompt).
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 * being rebased.
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
151 * command-line.
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
169 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
171 static int git_sequencer_config(const char *k, const char *v, void *cb)
173 struct replay_opts *opts = cb;
174 int status;
176 if (!strcmp(k, "commit.cleanup")) {
177 const char *s;
179 status = git_config_string(&s, k, v);
180 if (status)
181 return status;
183 if (!strcmp(s, "verbatim")) {
184 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
185 opts->explicit_cleanup = 1;
186 } else if (!strcmp(s, "whitespace")) {
187 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
188 opts->explicit_cleanup = 1;
189 } else if (!strcmp(s, "strip")) {
190 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
191 opts->explicit_cleanup = 1;
192 } else if (!strcmp(s, "scissors")) {
193 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
194 opts->explicit_cleanup = 1;
195 } else {
196 warning(_("invalid commit message cleanup mode '%s'"),
200 free((char *)s);
201 return status;
204 if (!strcmp(k, "commit.gpgsign")) {
205 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
206 return 0;
209 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
210 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
211 if (ret == 0) {
213 * pull.twohead is allowed to be multi-valued; we only
214 * care about the first value.
216 char *tmp = strchr(opts->default_strategy, ' ');
217 if (tmp)
218 *tmp = '\0';
220 return ret;
223 status = git_gpg_config(k, v, NULL);
224 if (status)
225 return status;
227 return git_diff_basic_config(k, v, NULL);
230 void sequencer_init_config(struct replay_opts *opts)
232 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
233 git_config(git_sequencer_config, opts);
236 static inline int is_rebase_i(const struct replay_opts *opts)
238 return opts->action == REPLAY_INTERACTIVE_REBASE;
241 static const char *get_dir(const struct replay_opts *opts)
243 if (is_rebase_i(opts))
244 return rebase_path();
245 return git_path_seq_dir();
248 static const char *get_todo_path(const struct replay_opts *opts)
250 if (is_rebase_i(opts))
251 return rebase_path_todo();
252 return git_path_todo_file();
256 * Returns 0 for non-conforming footer
257 * Returns 1 for conforming footer
258 * Returns 2 when sob exists within conforming footer
259 * Returns 3 when sob exists within conforming footer as last entry
261 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
262 size_t ignore_footer)
264 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
265 struct trailer_info info;
266 size_t i;
267 int found_sob = 0, found_sob_last = 0;
268 char saved_char;
270 opts.no_divider = 1;
272 if (ignore_footer) {
273 saved_char = sb->buf[sb->len - ignore_footer];
274 sb->buf[sb->len - ignore_footer] = '\0';
277 trailer_info_get(&info, sb->buf, &opts);
279 if (ignore_footer)
280 sb->buf[sb->len - ignore_footer] = saved_char;
282 if (info.trailer_start == info.trailer_end)
283 return 0;
285 for (i = 0; i < info.trailer_nr; i++)
286 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
287 found_sob = 1;
288 if (i == info.trailer_nr - 1)
289 found_sob_last = 1;
292 trailer_info_release(&info);
294 if (found_sob_last)
295 return 3;
296 if (found_sob)
297 return 2;
298 return 1;
301 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
303 static struct strbuf buf = STRBUF_INIT;
305 strbuf_reset(&buf);
306 if (opts->gpg_sign)
307 sq_quotef(&buf, "-S%s", opts->gpg_sign);
308 return buf.buf;
311 int sequencer_remove_state(struct replay_opts *opts)
313 struct strbuf buf = STRBUF_INIT;
314 int i, ret = 0;
316 if (is_rebase_i(opts) &&
317 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
318 char *p = buf.buf;
319 while (*p) {
320 char *eol = strchr(p, '\n');
321 if (eol)
322 *eol = '\0';
323 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
324 warning(_("could not delete '%s'"), p);
325 ret = -1;
327 if (!eol)
328 break;
329 p = eol + 1;
333 free(opts->gpg_sign);
334 free(opts->default_strategy);
335 free(opts->strategy);
336 for (i = 0; i < opts->xopts_nr; i++)
337 free(opts->xopts[i]);
338 free(opts->xopts);
339 strbuf_release(&opts->current_fixups);
341 strbuf_reset(&buf);
342 strbuf_addstr(&buf, get_dir(opts));
343 if (remove_dir_recursively(&buf, 0))
344 ret = error(_("could not remove '%s'"), buf.buf);
345 strbuf_release(&buf);
347 return ret;
350 static const char *action_name(const struct replay_opts *opts)
352 switch (opts->action) {
353 case REPLAY_REVERT:
354 return N_("revert");
355 case REPLAY_PICK:
356 return N_("cherry-pick");
357 case REPLAY_INTERACTIVE_REBASE:
358 return N_("rebase");
360 die(_("unknown action: %d"), opts->action);
363 struct commit_message {
364 char *parent_label;
365 char *label;
366 char *subject;
367 const char *message;
370 static const char *short_commit_name(struct commit *commit)
372 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
375 static int get_message(struct commit *commit, struct commit_message *out)
377 const char *abbrev, *subject;
378 int subject_len;
380 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
381 abbrev = short_commit_name(commit);
383 subject_len = find_commit_subject(out->message, &subject);
385 out->subject = xmemdupz(subject, subject_len);
386 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
387 out->parent_label = xstrfmt("parent of %s", out->label);
389 return 0;
392 static void free_message(struct commit *commit, struct commit_message *msg)
394 free(msg->parent_label);
395 free(msg->label);
396 free(msg->subject);
397 unuse_commit_buffer(commit, msg->message);
400 static void print_advice(struct repository *r, int show_hint,
401 struct replay_opts *opts)
403 char *msg = getenv("GIT_CHERRY_PICK_HELP");
405 if (msg) {
406 fprintf(stderr, "%s\n", msg);
408 * A conflict has occurred but the porcelain
409 * (typically rebase --interactive) wants to take care
410 * of the commit itself so remove CHERRY_PICK_HEAD
412 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
413 NULL, 0);
414 return;
417 if (show_hint) {
418 if (opts->no_commit)
419 advise(_("after resolving the conflicts, mark the corrected paths\n"
420 "with 'git add <paths>' or 'git rm <paths>'"));
421 else
422 advise(_("after resolving the conflicts, mark the corrected paths\n"
423 "with 'git add <paths>' or 'git rm <paths>'\n"
424 "and commit the result with 'git commit'"));
428 static int write_message(const void *buf, size_t len, const char *filename,
429 int append_eol)
431 struct lock_file msg_file = LOCK_INIT;
433 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
434 if (msg_fd < 0)
435 return error_errno(_("could not lock '%s'"), filename);
436 if (write_in_full(msg_fd, buf, len) < 0) {
437 error_errno(_("could not write to '%s'"), filename);
438 rollback_lock_file(&msg_file);
439 return -1;
441 if (append_eol && write(msg_fd, "\n", 1) < 0) {
442 error_errno(_("could not write eol to '%s'"), filename);
443 rollback_lock_file(&msg_file);
444 return -1;
446 if (commit_lock_file(&msg_file) < 0)
447 return error(_("failed to finalize '%s'"), filename);
449 return 0;
452 int read_oneliner(struct strbuf *buf,
453 const char *path, unsigned flags)
455 int orig_len = buf->len;
457 if (strbuf_read_file(buf, path, 0) < 0) {
458 if ((flags & READ_ONELINER_WARN_MISSING) ||
459 (errno != ENOENT && errno != ENOTDIR))
460 warning_errno(_("could not read '%s'"), path);
461 return 0;
464 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
465 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
466 --buf->len;
467 buf->buf[buf->len] = '\0';
470 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
471 return 0;
473 return 1;
476 static struct tree *empty_tree(struct repository *r)
478 return lookup_tree(r, the_hash_algo->empty_tree);
481 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
483 if (repo_read_index_unmerged(repo))
484 return error_resolve_conflict(_(action_name(opts)));
486 error(_("your local changes would be overwritten by %s."),
487 _(action_name(opts)));
489 if (advice_commit_before_merge)
490 advise(_("commit your changes or stash them to proceed."));
491 return -1;
494 static void update_abort_safety_file(void)
496 struct object_id head;
498 /* Do nothing on a single-pick */
499 if (!file_exists(git_path_seq_dir()))
500 return;
502 if (!get_oid("HEAD", &head))
503 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
504 else
505 write_file(git_path_abort_safety_file(), "%s", "");
508 static int fast_forward_to(struct repository *r,
509 const struct object_id *to,
510 const struct object_id *from,
511 int unborn,
512 struct replay_opts *opts)
514 struct ref_transaction *transaction;
515 struct strbuf sb = STRBUF_INIT;
516 struct strbuf err = STRBUF_INIT;
518 repo_read_index(r);
519 if (checkout_fast_forward(r, from, to, 1))
520 return -1; /* the callee should have complained already */
522 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
524 transaction = ref_transaction_begin(&err);
525 if (!transaction ||
526 ref_transaction_update(transaction, "HEAD",
527 to, unborn && !is_rebase_i(opts) ?
528 null_oid() : from,
529 0, sb.buf, &err) ||
530 ref_transaction_commit(transaction, &err)) {
531 ref_transaction_free(transaction);
532 error("%s", err.buf);
533 strbuf_release(&sb);
534 strbuf_release(&err);
535 return -1;
538 strbuf_release(&sb);
539 strbuf_release(&err);
540 ref_transaction_free(transaction);
541 update_abort_safety_file();
542 return 0;
545 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
546 int use_editor)
548 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
549 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
550 COMMIT_MSG_CLEANUP_SPACE;
551 else if (!strcmp(cleanup_arg, "verbatim"))
552 return COMMIT_MSG_CLEANUP_NONE;
553 else if (!strcmp(cleanup_arg, "whitespace"))
554 return COMMIT_MSG_CLEANUP_SPACE;
555 else if (!strcmp(cleanup_arg, "strip"))
556 return COMMIT_MSG_CLEANUP_ALL;
557 else if (!strcmp(cleanup_arg, "scissors"))
558 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
559 COMMIT_MSG_CLEANUP_SPACE;
560 else
561 die(_("Invalid cleanup mode %s"), cleanup_arg);
565 * NB using int rather than enum cleanup_mode to stop clang's
566 * -Wtautological-constant-out-of-range-compare complaining that the comparison
567 * is always true.
569 static const char *describe_cleanup_mode(int cleanup_mode)
571 static const char *modes[] = { "whitespace",
572 "verbatim",
573 "scissors",
574 "strip" };
576 if (cleanup_mode < ARRAY_SIZE(modes))
577 return modes[cleanup_mode];
579 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
582 void append_conflicts_hint(struct index_state *istate,
583 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
585 int i;
587 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
588 strbuf_addch(msgbuf, '\n');
589 wt_status_append_cut_line(msgbuf);
590 strbuf_addch(msgbuf, comment_line_char);
593 strbuf_addch(msgbuf, '\n');
594 strbuf_commented_addf(msgbuf, "Conflicts:\n");
595 for (i = 0; i < istate->cache_nr;) {
596 const struct cache_entry *ce = istate->cache[i++];
597 if (ce_stage(ce)) {
598 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
599 while (i < istate->cache_nr &&
600 !strcmp(ce->name, istate->cache[i]->name))
601 i++;
606 static int do_recursive_merge(struct repository *r,
607 struct commit *base, struct commit *next,
608 const char *base_label, const char *next_label,
609 struct object_id *head, struct strbuf *msgbuf,
610 struct replay_opts *opts)
612 struct merge_options o;
613 struct merge_result result;
614 struct tree *next_tree, *base_tree, *head_tree;
615 int clean, show_output;
616 int i;
617 struct lock_file index_lock = LOCK_INIT;
619 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
620 return -1;
622 repo_read_index(r);
624 init_merge_options(&o, r);
625 o.ancestor = base ? base_label : "(empty tree)";
626 o.branch1 = "HEAD";
627 o.branch2 = next ? next_label : "(empty tree)";
628 if (is_rebase_i(opts))
629 o.buffer_output = 2;
630 o.show_rename_progress = 1;
632 head_tree = parse_tree_indirect(head);
633 next_tree = next ? get_commit_tree(next) : empty_tree(r);
634 base_tree = base ? get_commit_tree(base) : empty_tree(r);
636 for (i = 0; i < opts->xopts_nr; i++)
637 parse_merge_opt(&o, opts->xopts[i]);
639 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
640 memset(&result, 0, sizeof(result));
641 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
642 &result);
643 show_output = !is_rebase_i(opts) || !result.clean;
645 * TODO: merge_switch_to_result will update index/working tree;
646 * we only really want to do that if !result.clean || this is
647 * the final patch to be picked. But determining this is the
648 * final patch would take some work, and "head_tree" would need
649 * to be replace with the tree the index matched before we
650 * started doing any picks.
652 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
653 clean = result.clean;
654 } else {
655 clean = merge_trees(&o, head_tree, next_tree, base_tree);
656 if (is_rebase_i(opts) && clean <= 0)
657 fputs(o.obuf.buf, stdout);
658 strbuf_release(&o.obuf);
660 if (clean < 0) {
661 rollback_lock_file(&index_lock);
662 return clean;
665 if (write_locked_index(r->index, &index_lock,
666 COMMIT_LOCK | SKIP_IF_UNCHANGED))
668 * TRANSLATORS: %s will be "revert", "cherry-pick" or
669 * "rebase".
671 return error(_("%s: Unable to write new index file"),
672 _(action_name(opts)));
674 if (!clean)
675 append_conflicts_hint(r->index, msgbuf,
676 opts->default_msg_cleanup);
678 return !clean;
681 static struct object_id *get_cache_tree_oid(struct index_state *istate)
683 if (!cache_tree_fully_valid(istate->cache_tree))
684 if (cache_tree_update(istate, 0)) {
685 error(_("unable to update cache tree"));
686 return NULL;
689 return &istate->cache_tree->oid;
692 static int is_index_unchanged(struct repository *r)
694 struct object_id head_oid, *cache_tree_oid;
695 struct commit *head_commit;
696 struct index_state *istate = r->index;
698 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
699 return error(_("could not resolve HEAD commit"));
701 head_commit = lookup_commit(r, &head_oid);
704 * If head_commit is NULL, check_commit, called from
705 * lookup_commit, would have indicated that head_commit is not
706 * a commit object already. parse_commit() will return failure
707 * without further complaints in such a case. Otherwise, if
708 * the commit is invalid, parse_commit() will complain. So
709 * there is nothing for us to say here. Just return failure.
711 if (parse_commit(head_commit))
712 return -1;
714 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
715 return -1;
717 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
720 static int write_author_script(const char *message)
722 struct strbuf buf = STRBUF_INIT;
723 const char *eol;
724 int res;
726 for (;;)
727 if (!*message || starts_with(message, "\n")) {
728 missing_author:
729 /* Missing 'author' line? */
730 unlink(rebase_path_author_script());
731 return 0;
732 } else if (skip_prefix(message, "author ", &message))
733 break;
734 else if ((eol = strchr(message, '\n')))
735 message = eol + 1;
736 else
737 goto missing_author;
739 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
740 while (*message && *message != '\n' && *message != '\r')
741 if (skip_prefix(message, " <", &message))
742 break;
743 else if (*message != '\'')
744 strbuf_addch(&buf, *(message++));
745 else
746 strbuf_addf(&buf, "'\\%c'", *(message++));
747 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
748 while (*message && *message != '\n' && *message != '\r')
749 if (skip_prefix(message, "> ", &message))
750 break;
751 else if (*message != '\'')
752 strbuf_addch(&buf, *(message++));
753 else
754 strbuf_addf(&buf, "'\\%c'", *(message++));
755 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
756 while (*message && *message != '\n' && *message != '\r')
757 if (*message != '\'')
758 strbuf_addch(&buf, *(message++));
759 else
760 strbuf_addf(&buf, "'\\%c'", *(message++));
761 strbuf_addch(&buf, '\'');
762 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
763 strbuf_release(&buf);
764 return res;
768 * Take a series of KEY='VALUE' lines where VALUE part is
769 * sq-quoted, and append <KEY, VALUE> at the end of the string list
771 static int parse_key_value_squoted(char *buf, struct string_list *list)
773 while (*buf) {
774 struct string_list_item *item;
775 char *np;
776 char *cp = strchr(buf, '=');
777 if (!cp) {
778 np = strchrnul(buf, '\n');
779 return error(_("no key present in '%.*s'"),
780 (int) (np - buf), buf);
782 np = strchrnul(cp, '\n');
783 *cp++ = '\0';
784 item = string_list_append(list, buf);
786 buf = np + (*np == '\n');
787 *np = '\0';
788 cp = sq_dequote(cp);
789 if (!cp)
790 return error(_("unable to dequote value of '%s'"),
791 item->string);
792 item->util = xstrdup(cp);
794 return 0;
798 * Reads and parses the state directory's "author-script" file, and sets name,
799 * email and date accordingly.
800 * Returns 0 on success, -1 if the file could not be parsed.
802 * The author script is of the format:
804 * GIT_AUTHOR_NAME='$author_name'
805 * GIT_AUTHOR_EMAIL='$author_email'
806 * GIT_AUTHOR_DATE='$author_date'
808 * where $author_name, $author_email and $author_date are quoted. We are strict
809 * with our parsing, as the file was meant to be eval'd in the now-removed
810 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
811 * from what this function expects, it is better to bail out than to do
812 * something that the user does not expect.
814 int read_author_script(const char *path, char **name, char **email, char **date,
815 int allow_missing)
817 struct strbuf buf = STRBUF_INIT;
818 struct string_list kv = STRING_LIST_INIT_DUP;
819 int retval = -1; /* assume failure */
820 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
822 if (strbuf_read_file(&buf, path, 256) <= 0) {
823 strbuf_release(&buf);
824 if (errno == ENOENT && allow_missing)
825 return 0;
826 else
827 return error_errno(_("could not open '%s' for reading"),
828 path);
831 if (parse_key_value_squoted(buf.buf, &kv))
832 goto finish;
834 for (i = 0; i < kv.nr; i++) {
835 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
836 if (name_i != -2)
837 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
838 else
839 name_i = i;
840 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
841 if (email_i != -2)
842 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
843 else
844 email_i = i;
845 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
846 if (date_i != -2)
847 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
848 else
849 date_i = i;
850 } else {
851 err = error(_("unknown variable '%s'"),
852 kv.items[i].string);
855 if (name_i == -2)
856 error(_("missing 'GIT_AUTHOR_NAME'"));
857 if (email_i == -2)
858 error(_("missing 'GIT_AUTHOR_EMAIL'"));
859 if (date_i == -2)
860 error(_("missing 'GIT_AUTHOR_DATE'"));
861 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
862 goto finish;
863 *name = kv.items[name_i].util;
864 *email = kv.items[email_i].util;
865 *date = kv.items[date_i].util;
866 retval = 0;
867 finish:
868 string_list_clear(&kv, !!retval);
869 strbuf_release(&buf);
870 return retval;
874 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
875 * file with shell quoting into struct strvec. Returns -1 on
876 * error, 0 otherwise.
878 static int read_env_script(struct strvec *env)
880 char *name, *email, *date;
882 if (read_author_script(rebase_path_author_script(),
883 &name, &email, &date, 0))
884 return -1;
886 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
887 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
888 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
889 free(name);
890 free(email);
891 free(date);
893 return 0;
896 static char *get_author(const char *message)
898 size_t len;
899 const char *a;
901 a = find_commit_header(message, "author", &len);
902 if (a)
903 return xmemdupz(a, len);
905 return NULL;
908 static const char *author_date_from_env_array(const struct strvec *env)
910 int i;
911 const char *date;
913 for (i = 0; i < env->nr; i++)
914 if (skip_prefix(env->v[i],
915 "GIT_AUTHOR_DATE=", &date))
916 return date;
918 * If GIT_AUTHOR_DATE is missing we should have already errored out when
919 * reading the script
921 BUG("GIT_AUTHOR_DATE missing from author script");
924 static const char staged_changes_advice[] =
925 N_("you have staged changes in your working tree\n"
926 "If these changes are meant to be squashed into the previous commit, run:\n"
927 "\n"
928 " git commit --amend %s\n"
929 "\n"
930 "If they are meant to go into a new commit, run:\n"
931 "\n"
932 " git commit %s\n"
933 "\n"
934 "In both cases, once you're done, continue with:\n"
935 "\n"
936 " git rebase --continue\n");
938 #define ALLOW_EMPTY (1<<0)
939 #define EDIT_MSG (1<<1)
940 #define AMEND_MSG (1<<2)
941 #define CLEANUP_MSG (1<<3)
942 #define VERIFY_MSG (1<<4)
943 #define CREATE_ROOT_COMMIT (1<<5)
944 #define VERBATIM_MSG (1<<6)
946 static int run_command_silent_on_success(struct child_process *cmd)
948 struct strbuf buf = STRBUF_INIT;
949 int rc;
951 cmd->stdout_to_stderr = 1;
952 rc = pipe_command(cmd,
953 NULL, 0,
954 NULL, 0,
955 &buf, 0);
957 if (rc)
958 fputs(buf.buf, stderr);
959 strbuf_release(&buf);
960 return rc;
964 * If we are cherry-pick, and if the merge did not result in
965 * hand-editing, we will hit this commit and inherit the original
966 * author date and name.
968 * If we are revert, or if our cherry-pick results in a hand merge,
969 * we had better say that the current user is responsible for that.
971 * An exception is when run_git_commit() is called during an
972 * interactive rebase: in that case, we will want to retain the
973 * author metadata.
975 static int run_git_commit(const char *defmsg,
976 struct replay_opts *opts,
977 unsigned int flags)
979 struct child_process cmd = CHILD_PROCESS_INIT;
981 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
982 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
984 cmd.git_cmd = 1;
986 if (is_rebase_i(opts) && !(!defmsg && (flags & AMEND_MSG)) &&
987 read_env_script(&cmd.env_array)) {
988 const char *gpg_opt = gpg_sign_opt_quoted(opts);
990 return error(_(staged_changes_advice),
991 gpg_opt, gpg_opt);
994 if (opts->committer_date_is_author_date)
995 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
996 opts->ignore_date ?
997 "" :
998 author_date_from_env_array(&cmd.env_array));
999 if (opts->ignore_date)
1000 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1002 strvec_push(&cmd.args, "commit");
1004 if (!(flags & VERIFY_MSG))
1005 strvec_push(&cmd.args, "-n");
1006 if ((flags & AMEND_MSG))
1007 strvec_push(&cmd.args, "--amend");
1008 if (opts->gpg_sign)
1009 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1010 else
1011 strvec_push(&cmd.args, "--no-gpg-sign");
1012 if (defmsg)
1013 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1014 else if (!(flags & EDIT_MSG))
1015 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1016 if ((flags & CLEANUP_MSG))
1017 strvec_push(&cmd.args, "--cleanup=strip");
1018 if ((flags & VERBATIM_MSG))
1019 strvec_push(&cmd.args, "--cleanup=verbatim");
1020 if ((flags & EDIT_MSG))
1021 strvec_push(&cmd.args, "-e");
1022 else if (!(flags & CLEANUP_MSG) &&
1023 !opts->signoff && !opts->record_origin &&
1024 !opts->explicit_cleanup)
1025 strvec_push(&cmd.args, "--cleanup=verbatim");
1027 if ((flags & ALLOW_EMPTY))
1028 strvec_push(&cmd.args, "--allow-empty");
1030 if (!(flags & EDIT_MSG))
1031 strvec_push(&cmd.args, "--allow-empty-message");
1033 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1034 return run_command_silent_on_success(&cmd);
1035 else
1036 return run_command(&cmd);
1039 static int rest_is_empty(const struct strbuf *sb, int start)
1041 int i, eol;
1042 const char *nl;
1044 /* Check if the rest is just whitespace and Signed-off-by's. */
1045 for (i = start; i < sb->len; i++) {
1046 nl = memchr(sb->buf + i, '\n', sb->len - i);
1047 if (nl)
1048 eol = nl - sb->buf;
1049 else
1050 eol = sb->len;
1052 if (strlen(sign_off_header) <= eol - i &&
1053 starts_with(sb->buf + i, sign_off_header)) {
1054 i = eol;
1055 continue;
1057 while (i < eol)
1058 if (!isspace(sb->buf[i++]))
1059 return 0;
1062 return 1;
1065 void cleanup_message(struct strbuf *msgbuf,
1066 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1068 if (verbose || /* Truncate the message just before the diff, if any. */
1069 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1070 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1071 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1072 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1076 * Find out if the message in the strbuf contains only whitespace and
1077 * Signed-off-by lines.
1079 int message_is_empty(const struct strbuf *sb,
1080 enum commit_msg_cleanup_mode cleanup_mode)
1082 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1083 return 0;
1084 return rest_is_empty(sb, 0);
1088 * See if the user edited the message in the editor or left what
1089 * was in the template intact
1091 int template_untouched(const struct strbuf *sb, const char *template_file,
1092 enum commit_msg_cleanup_mode cleanup_mode)
1094 struct strbuf tmpl = STRBUF_INIT;
1095 const char *start;
1097 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1098 return 0;
1100 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1101 return 0;
1103 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1104 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1105 start = sb->buf;
1106 strbuf_release(&tmpl);
1107 return rest_is_empty(sb, start - sb->buf);
1110 int update_head_with_reflog(const struct commit *old_head,
1111 const struct object_id *new_head,
1112 const char *action, const struct strbuf *msg,
1113 struct strbuf *err)
1115 struct ref_transaction *transaction;
1116 struct strbuf sb = STRBUF_INIT;
1117 const char *nl;
1118 int ret = 0;
1120 if (action) {
1121 strbuf_addstr(&sb, action);
1122 strbuf_addstr(&sb, ": ");
1125 nl = strchr(msg->buf, '\n');
1126 if (nl) {
1127 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1128 } else {
1129 strbuf_addbuf(&sb, msg);
1130 strbuf_addch(&sb, '\n');
1133 transaction = ref_transaction_begin(err);
1134 if (!transaction ||
1135 ref_transaction_update(transaction, "HEAD", new_head,
1136 old_head ? &old_head->object.oid : null_oid(),
1137 0, sb.buf, err) ||
1138 ref_transaction_commit(transaction, err)) {
1139 ret = -1;
1141 ref_transaction_free(transaction);
1142 strbuf_release(&sb);
1144 return ret;
1147 static int run_rewrite_hook(const struct object_id *oldoid,
1148 const struct object_id *newoid)
1150 struct child_process proc = CHILD_PROCESS_INIT;
1151 const char *argv[3];
1152 int code;
1153 struct strbuf sb = STRBUF_INIT;
1155 argv[0] = find_hook("post-rewrite");
1156 if (!argv[0])
1157 return 0;
1159 argv[1] = "amend";
1160 argv[2] = NULL;
1162 proc.argv = argv;
1163 proc.in = -1;
1164 proc.stdout_to_stderr = 1;
1165 proc.trace2_hook_name = "post-rewrite";
1167 code = start_command(&proc);
1168 if (code)
1169 return code;
1170 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1171 sigchain_push(SIGPIPE, SIG_IGN);
1172 write_in_full(proc.in, sb.buf, sb.len);
1173 close(proc.in);
1174 strbuf_release(&sb);
1175 sigchain_pop(SIGPIPE);
1176 return finish_command(&proc);
1179 void commit_post_rewrite(struct repository *r,
1180 const struct commit *old_head,
1181 const struct object_id *new_head)
1183 struct notes_rewrite_cfg *cfg;
1185 cfg = init_copy_notes_for_rewrite("amend");
1186 if (cfg) {
1187 /* we are amending, so old_head is not NULL */
1188 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1189 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1191 run_rewrite_hook(&old_head->object.oid, new_head);
1194 static int run_prepare_commit_msg_hook(struct repository *r,
1195 struct strbuf *msg,
1196 const char *commit)
1198 int ret = 0;
1199 const char *name, *arg1 = NULL, *arg2 = NULL;
1201 name = git_path_commit_editmsg();
1202 if (write_message(msg->buf, msg->len, name, 0))
1203 return -1;
1205 if (commit) {
1206 arg1 = "commit";
1207 arg2 = commit;
1208 } else {
1209 arg1 = "message";
1211 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1212 arg1, arg2, NULL))
1213 ret = error(_("'prepare-commit-msg' hook failed"));
1215 return ret;
1218 static const char implicit_ident_advice_noconfig[] =
1219 N_("Your name and email address were configured automatically based\n"
1220 "on your username and hostname. Please check that they are accurate.\n"
1221 "You can suppress this message by setting them explicitly. Run the\n"
1222 "following command and follow the instructions in your editor to edit\n"
1223 "your configuration file:\n"
1224 "\n"
1225 " git config --global --edit\n"
1226 "\n"
1227 "After doing this, you may fix the identity used for this commit with:\n"
1228 "\n"
1229 " git commit --amend --reset-author\n");
1231 static const char implicit_ident_advice_config[] =
1232 N_("Your name and email address were configured automatically based\n"
1233 "on your username and hostname. Please check that they are accurate.\n"
1234 "You can suppress this message by setting them explicitly:\n"
1235 "\n"
1236 " git config --global user.name \"Your Name\"\n"
1237 " git config --global user.email you@example.com\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 " git commit --amend --reset-author\n");
1243 static const char *implicit_ident_advice(void)
1245 char *user_config = expand_user_path("~/.gitconfig", 0);
1246 char *xdg_config = xdg_config_home("config");
1247 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1249 free(user_config);
1250 free(xdg_config);
1252 if (config_exists)
1253 return _(implicit_ident_advice_config);
1254 else
1255 return _(implicit_ident_advice_noconfig);
1259 void print_commit_summary(struct repository *r,
1260 const char *prefix,
1261 const struct object_id *oid,
1262 unsigned int flags)
1264 struct rev_info rev;
1265 struct commit *commit;
1266 struct strbuf format = STRBUF_INIT;
1267 const char *head;
1268 struct pretty_print_context pctx = {0};
1269 struct strbuf author_ident = STRBUF_INIT;
1270 struct strbuf committer_ident = STRBUF_INIT;
1272 commit = lookup_commit(r, oid);
1273 if (!commit)
1274 die(_("couldn't look up newly created commit"));
1275 if (parse_commit(commit))
1276 die(_("could not parse newly created commit"));
1278 strbuf_addstr(&format, "format:%h] %s");
1280 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1281 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1282 if (strbuf_cmp(&author_ident, &committer_ident)) {
1283 strbuf_addstr(&format, "\n Author: ");
1284 strbuf_addbuf_percentquote(&format, &author_ident);
1286 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1287 struct strbuf date = STRBUF_INIT;
1289 format_commit_message(commit, "%ad", &date, &pctx);
1290 strbuf_addstr(&format, "\n Date: ");
1291 strbuf_addbuf_percentquote(&format, &date);
1292 strbuf_release(&date);
1294 if (!committer_ident_sufficiently_given()) {
1295 strbuf_addstr(&format, "\n Committer: ");
1296 strbuf_addbuf_percentquote(&format, &committer_ident);
1297 if (advice_implicit_identity) {
1298 strbuf_addch(&format, '\n');
1299 strbuf_addstr(&format, implicit_ident_advice());
1302 strbuf_release(&author_ident);
1303 strbuf_release(&committer_ident);
1305 repo_init_revisions(r, &rev, prefix);
1306 setup_revisions(0, NULL, &rev, NULL);
1308 rev.diff = 1;
1309 rev.diffopt.output_format =
1310 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1312 rev.verbose_header = 1;
1313 rev.show_root_diff = 1;
1314 get_commit_format(format.buf, &rev);
1315 rev.always_show_header = 0;
1316 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1317 rev.diffopt.break_opt = 0;
1318 diff_setup_done(&rev.diffopt);
1320 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1321 if (!head)
1322 die_errno(_("unable to resolve HEAD after creating commit"));
1323 if (!strcmp(head, "HEAD"))
1324 head = _("detached HEAD");
1325 else
1326 skip_prefix(head, "refs/heads/", &head);
1327 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1328 _(" (root-commit)") : "");
1330 if (!log_tree_commit(&rev, commit)) {
1331 rev.always_show_header = 1;
1332 rev.use_terminator = 1;
1333 log_tree_commit(&rev, commit);
1336 strbuf_release(&format);
1339 static int parse_head(struct repository *r, struct commit **head)
1341 struct commit *current_head;
1342 struct object_id oid;
1344 if (get_oid("HEAD", &oid)) {
1345 current_head = NULL;
1346 } else {
1347 current_head = lookup_commit_reference(r, &oid);
1348 if (!current_head)
1349 return error(_("could not parse HEAD"));
1350 if (!oideq(&oid, &current_head->object.oid)) {
1351 warning(_("HEAD %s is not a commit!"),
1352 oid_to_hex(&oid));
1354 if (parse_commit(current_head))
1355 return error(_("could not parse HEAD commit"));
1357 *head = current_head;
1359 return 0;
1363 * Try to commit without forking 'git commit'. In some cases we need
1364 * to run 'git commit' to display an error message
1366 * Returns:
1367 * -1 - error unable to commit
1368 * 0 - success
1369 * 1 - run 'git commit'
1371 static int try_to_commit(struct repository *r,
1372 struct strbuf *msg, const char *author,
1373 struct replay_opts *opts, unsigned int flags,
1374 struct object_id *oid)
1376 struct object_id tree;
1377 struct commit *current_head = NULL;
1378 struct commit_list *parents = NULL;
1379 struct commit_extra_header *extra = NULL;
1380 struct strbuf err = STRBUF_INIT;
1381 struct strbuf commit_msg = STRBUF_INIT;
1382 char *amend_author = NULL;
1383 const char *committer = NULL;
1384 const char *hook_commit = NULL;
1385 enum commit_msg_cleanup_mode cleanup;
1386 int res = 0;
1388 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1389 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1391 if (parse_head(r, &current_head))
1392 return -1;
1394 if (flags & AMEND_MSG) {
1395 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1396 const char *out_enc = get_commit_output_encoding();
1397 const char *message = logmsg_reencode(current_head, NULL,
1398 out_enc);
1400 if (!msg) {
1401 const char *orig_message = NULL;
1403 find_commit_subject(message, &orig_message);
1404 msg = &commit_msg;
1405 strbuf_addstr(msg, orig_message);
1406 hook_commit = "HEAD";
1408 author = amend_author = get_author(message);
1409 unuse_commit_buffer(current_head, message);
1410 if (!author) {
1411 res = error(_("unable to parse commit author"));
1412 goto out;
1414 parents = copy_commit_list(current_head->parents);
1415 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1416 } else if (current_head &&
1417 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1418 commit_list_insert(current_head, &parents);
1421 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1422 res = error(_("git write-tree failed to write a tree"));
1423 goto out;
1426 if (!(flags & ALLOW_EMPTY)) {
1427 struct commit *first_parent = current_head;
1429 if (flags & AMEND_MSG) {
1430 if (current_head->parents) {
1431 first_parent = current_head->parents->item;
1432 if (repo_parse_commit(r, first_parent)) {
1433 res = error(_("could not parse HEAD commit"));
1434 goto out;
1436 } else {
1437 first_parent = NULL;
1440 if (oideq(first_parent
1441 ? get_commit_tree_oid(first_parent)
1442 : the_hash_algo->empty_tree,
1443 &tree)) {
1444 res = 1; /* run 'git commit' to display error message */
1445 goto out;
1449 if (find_hook("prepare-commit-msg")) {
1450 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1451 if (res)
1452 goto out;
1453 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1454 2048) < 0) {
1455 res = error_errno(_("unable to read commit message "
1456 "from '%s'"),
1457 git_path_commit_editmsg());
1458 goto out;
1460 msg = &commit_msg;
1463 if (flags & CLEANUP_MSG)
1464 cleanup = COMMIT_MSG_CLEANUP_ALL;
1465 else if (flags & VERBATIM_MSG)
1466 cleanup = COMMIT_MSG_CLEANUP_NONE;
1467 else if ((opts->signoff || opts->record_origin) &&
1468 !opts->explicit_cleanup)
1469 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1470 else
1471 cleanup = opts->default_msg_cleanup;
1473 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1474 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1475 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1476 res = 1; /* run 'git commit' to display error message */
1477 goto out;
1480 if (opts->committer_date_is_author_date) {
1481 struct ident_split id;
1482 struct strbuf date = STRBUF_INIT;
1484 if (!opts->ignore_date) {
1485 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1486 res = error(_("invalid author identity '%s'"),
1487 author);
1488 goto out;
1490 if (!id.date_begin) {
1491 res = error(_(
1492 "corrupt author: missing date information"));
1493 goto out;
1495 strbuf_addf(&date, "@%.*s %.*s",
1496 (int)(id.date_end - id.date_begin),
1497 id.date_begin,
1498 (int)(id.tz_end - id.tz_begin),
1499 id.tz_begin);
1500 } else {
1501 reset_ident_date();
1503 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1504 getenv("GIT_COMMITTER_EMAIL"),
1505 WANT_COMMITTER_IDENT,
1506 opts->ignore_date ? NULL : date.buf,
1507 IDENT_STRICT);
1508 strbuf_release(&date);
1509 } else {
1510 reset_ident_date();
1513 if (opts->ignore_date) {
1514 struct ident_split id;
1515 char *name, *email;
1517 if (split_ident_line(&id, author, strlen(author)) < 0) {
1518 error(_("invalid author identity '%s'"), author);
1519 goto out;
1521 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1522 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1523 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1524 IDENT_STRICT);
1525 free(name);
1526 free(email);
1529 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1530 author, committer, opts->gpg_sign, extra)) {
1531 res = error(_("failed to write commit object"));
1532 goto out;
1535 if (update_head_with_reflog(current_head, oid,
1536 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1537 res = error("%s", err.buf);
1538 goto out;
1541 run_commit_hook(0, r->index_file, "post-commit", NULL);
1542 if (flags & AMEND_MSG)
1543 commit_post_rewrite(r, current_head, oid);
1545 out:
1546 free_commit_extra_headers(extra);
1547 strbuf_release(&err);
1548 strbuf_release(&commit_msg);
1549 free(amend_author);
1551 return res;
1554 static int write_rebase_head(struct object_id *oid)
1556 if (update_ref("rebase", "REBASE_HEAD", oid,
1557 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1558 return error(_("could not update %s"), "REBASE_HEAD");
1560 return 0;
1563 static int do_commit(struct repository *r,
1564 const char *msg_file, const char *author,
1565 struct replay_opts *opts, unsigned int flags,
1566 struct object_id *oid)
1568 int res = 1;
1570 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1571 struct object_id oid;
1572 struct strbuf sb = STRBUF_INIT;
1574 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1575 return error_errno(_("unable to read commit message "
1576 "from '%s'"),
1577 msg_file);
1579 res = try_to_commit(r, msg_file ? &sb : NULL,
1580 author, opts, flags, &oid);
1581 strbuf_release(&sb);
1582 if (!res) {
1583 refs_delete_ref(get_main_ref_store(r), "",
1584 "CHERRY_PICK_HEAD", NULL, 0);
1585 unlink(git_path_merge_msg(r));
1586 if (!is_rebase_i(opts))
1587 print_commit_summary(r, NULL, &oid,
1588 SUMMARY_SHOW_AUTHOR_DATE);
1589 return res;
1592 if (res == 1) {
1593 if (is_rebase_i(opts) && oid)
1594 if (write_rebase_head(oid))
1595 return -1;
1596 return run_git_commit(msg_file, opts, flags);
1599 return res;
1602 static int is_original_commit_empty(struct commit *commit)
1604 const struct object_id *ptree_oid;
1606 if (parse_commit(commit))
1607 return error(_("could not parse commit %s"),
1608 oid_to_hex(&commit->object.oid));
1609 if (commit->parents) {
1610 struct commit *parent = commit->parents->item;
1611 if (parse_commit(parent))
1612 return error(_("could not parse parent commit %s"),
1613 oid_to_hex(&parent->object.oid));
1614 ptree_oid = get_commit_tree_oid(parent);
1615 } else {
1616 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1619 return oideq(ptree_oid, get_commit_tree_oid(commit));
1623 * Should empty commits be allowed? Return status:
1624 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1625 * 0: Halt on empty commit
1626 * 1: Allow empty commit
1627 * 2: Drop empty commit
1629 static int allow_empty(struct repository *r,
1630 struct replay_opts *opts,
1631 struct commit *commit)
1633 int index_unchanged, originally_empty;
1636 * Four cases:
1638 * (1) we do not allow empty at all and error out.
1640 * (2) we allow ones that were initially empty, and
1641 * just drop the ones that become empty
1643 * (3) we allow ones that were initially empty, but
1644 * halt for the ones that become empty;
1646 * (4) we allow both.
1648 if (!opts->allow_empty)
1649 return 0; /* let "git commit" barf as necessary */
1651 index_unchanged = is_index_unchanged(r);
1652 if (index_unchanged < 0)
1653 return index_unchanged;
1654 if (!index_unchanged)
1655 return 0; /* we do not have to say --allow-empty */
1657 if (opts->keep_redundant_commits)
1658 return 1;
1660 originally_empty = is_original_commit_empty(commit);
1661 if (originally_empty < 0)
1662 return originally_empty;
1663 if (originally_empty)
1664 return 1;
1665 else if (opts->drop_redundant_commits)
1666 return 2;
1667 else
1668 return 0;
1671 static struct {
1672 char c;
1673 const char *str;
1674 } todo_command_info[] = {
1675 { 'p', "pick" },
1676 { 0, "revert" },
1677 { 'e', "edit" },
1678 { 'r', "reword" },
1679 { 'f', "fixup" },
1680 { 's', "squash" },
1681 { 'x', "exec" },
1682 { 'b', "break" },
1683 { 'l', "label" },
1684 { 't', "reset" },
1685 { 'm', "merge" },
1686 { 0, "noop" },
1687 { 'd', "drop" },
1688 { 0, NULL }
1691 static const char *command_to_string(const enum todo_command command)
1693 if (command < TODO_COMMENT)
1694 return todo_command_info[command].str;
1695 die(_("unknown command: %d"), command);
1698 static char command_to_char(const enum todo_command command)
1700 if (command < TODO_COMMENT)
1701 return todo_command_info[command].c;
1702 return comment_line_char;
1705 static int is_noop(const enum todo_command command)
1707 return TODO_NOOP <= command;
1710 static int is_fixup(enum todo_command command)
1712 return command == TODO_FIXUP || command == TODO_SQUASH;
1715 /* Does this command create a (non-merge) commit? */
1716 static int is_pick_or_similar(enum todo_command command)
1718 switch (command) {
1719 case TODO_PICK:
1720 case TODO_REVERT:
1721 case TODO_EDIT:
1722 case TODO_REWORD:
1723 case TODO_FIXUP:
1724 case TODO_SQUASH:
1725 return 1;
1726 default:
1727 return 0;
1731 enum todo_item_flags {
1732 TODO_EDIT_MERGE_MSG = (1 << 0),
1733 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1734 TODO_EDIT_FIXUP_MSG = (1 << 2),
1737 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1738 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1739 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1740 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1741 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1743 static int is_fixup_flag(enum todo_command command, unsigned flag)
1745 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1746 (flag & TODO_EDIT_FIXUP_MSG));
1750 * Wrapper around strbuf_add_commented_lines() which avoids double
1751 * commenting commit subjects.
1753 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1755 const char *s = str;
1756 while (len > 0 && s[0] == comment_line_char) {
1757 size_t count;
1758 const char *n = memchr(s, '\n', len);
1759 if (!n)
1760 count = len;
1761 else
1762 count = n - s + 1;
1763 strbuf_add(buf, s, count);
1764 s += count;
1765 len -= count;
1767 strbuf_add_commented_lines(buf, s, len);
1770 /* Does the current fixup chain contain a squash command? */
1771 static int seen_squash(struct replay_opts *opts)
1773 return starts_with(opts->current_fixups.buf, "squash") ||
1774 strstr(opts->current_fixups.buf, "\nsquash");
1777 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1779 strbuf_setlen(buf1, 2);
1780 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1781 strbuf_addch(buf1, '\n');
1782 strbuf_setlen(buf2, 2);
1783 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1784 strbuf_addch(buf2, '\n');
1788 * Comment out any un-commented commit messages, updating the message comments
1789 * to say they will be skipped but do not comment out the empty lines that
1790 * surround commit messages and their comments.
1792 static void update_squash_message_for_fixup(struct strbuf *msg)
1794 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1795 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1796 const char *s, *start;
1797 char *orig_msg;
1798 size_t orig_msg_len;
1799 int i = 1;
1801 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1802 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1803 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1804 while (s) {
1805 const char *next;
1806 size_t off;
1807 if (skip_prefix(s, buf1.buf, &next)) {
1809 * Copy the last message, preserving the blank line
1810 * preceding the current line
1812 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1813 copy_lines(msg, start, s - start - off);
1814 if (off)
1815 strbuf_addch(msg, '\n');
1817 * The next message needs to be commented out but the
1818 * message header is already commented out so just copy
1819 * it and the blank line that follows it.
1821 strbuf_addbuf(msg, &buf2);
1822 if (*next == '\n')
1823 strbuf_addch(msg, *next++);
1824 start = s = next;
1825 copy_lines = add_commented_lines;
1826 update_comment_bufs(&buf1, &buf2, ++i);
1827 } else if (skip_prefix(s, buf2.buf, &next)) {
1828 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1829 copy_lines(msg, start, s - start - off);
1830 start = s - off;
1831 s = next;
1832 copy_lines = strbuf_add;
1833 update_comment_bufs(&buf1, &buf2, ++i);
1834 } else {
1835 s = strchr(s, '\n');
1836 if (s)
1837 s++;
1840 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1841 free(orig_msg);
1842 strbuf_release(&buf1);
1843 strbuf_release(&buf2);
1846 static int append_squash_message(struct strbuf *buf, const char *body,
1847 enum todo_command command, struct replay_opts *opts,
1848 unsigned flag)
1850 const char *fixup_msg;
1851 size_t commented_len = 0, fixup_off;
1853 * amend is non-interactive and not normally used with fixup!
1854 * or squash! commits, so only comment out those subjects when
1855 * squashing commit messages.
1857 if (starts_with(body, "amend!") ||
1858 ((command == TODO_SQUASH || seen_squash(opts)) &&
1859 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1860 commented_len = commit_subject_length(body);
1862 strbuf_addf(buf, "\n%c ", comment_line_char);
1863 strbuf_addf(buf, _(nth_commit_msg_fmt),
1864 ++opts->current_fixup_count + 1);
1865 strbuf_addstr(buf, "\n\n");
1866 strbuf_add_commented_lines(buf, body, commented_len);
1867 /* buf->buf may be reallocated so store an offset into the buffer */
1868 fixup_off = buf->len;
1869 strbuf_addstr(buf, body + commented_len);
1871 /* fixup -C after squash behaves like squash */
1872 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1874 * We're replacing the commit message so we need to
1875 * append the Signed-off-by: trailer if the user
1876 * requested '--signoff'.
1878 if (opts->signoff)
1879 append_signoff(buf, 0, 0);
1881 if ((command == TODO_FIXUP) &&
1882 (flag & TODO_REPLACE_FIXUP_MSG) &&
1883 (file_exists(rebase_path_fixup_msg()) ||
1884 !file_exists(rebase_path_squash_msg()))) {
1885 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1886 if (write_message(fixup_msg, strlen(fixup_msg),
1887 rebase_path_fixup_msg(), 0) < 0)
1888 return error(_("cannot write '%s'"),
1889 rebase_path_fixup_msg());
1890 } else {
1891 unlink(rebase_path_fixup_msg());
1893 } else {
1894 unlink(rebase_path_fixup_msg());
1897 return 0;
1900 static int update_squash_messages(struct repository *r,
1901 enum todo_command command,
1902 struct commit *commit,
1903 struct replay_opts *opts,
1904 unsigned flag)
1906 struct strbuf buf = STRBUF_INIT;
1907 int res = 0;
1908 const char *message, *body;
1909 const char *encoding = get_commit_output_encoding();
1911 if (opts->current_fixup_count > 0) {
1912 struct strbuf header = STRBUF_INIT;
1913 char *eol;
1915 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1916 return error(_("could not read '%s'"),
1917 rebase_path_squash_msg());
1919 eol = buf.buf[0] != comment_line_char ?
1920 buf.buf : strchrnul(buf.buf, '\n');
1922 strbuf_addf(&header, "%c ", comment_line_char);
1923 strbuf_addf(&header, _(combined_commit_msg_fmt),
1924 opts->current_fixup_count + 2);
1925 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1926 strbuf_release(&header);
1927 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1928 update_squash_message_for_fixup(&buf);
1929 } else {
1930 struct object_id head;
1931 struct commit *head_commit;
1932 const char *head_message, *body;
1934 if (get_oid("HEAD", &head))
1935 return error(_("need a HEAD to fixup"));
1936 if (!(head_commit = lookup_commit_reference(r, &head)))
1937 return error(_("could not read HEAD"));
1938 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1939 return error(_("could not read HEAD's commit message"));
1941 find_commit_subject(head_message, &body);
1942 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1943 rebase_path_fixup_msg(), 0) < 0) {
1944 unuse_commit_buffer(head_commit, head_message);
1945 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1947 strbuf_addf(&buf, "%c ", comment_line_char);
1948 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1949 strbuf_addf(&buf, "\n%c ", comment_line_char);
1950 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1951 _(skip_first_commit_msg_str) :
1952 _(first_commit_msg_str));
1953 strbuf_addstr(&buf, "\n\n");
1954 if (is_fixup_flag(command, flag))
1955 strbuf_add_commented_lines(&buf, body, strlen(body));
1956 else
1957 strbuf_addstr(&buf, body);
1959 unuse_commit_buffer(head_commit, head_message);
1962 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1963 return error(_("could not read commit message of %s"),
1964 oid_to_hex(&commit->object.oid));
1965 find_commit_subject(message, &body);
1967 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1968 res = append_squash_message(&buf, body, command, opts, flag);
1969 } else if (command == TODO_FIXUP) {
1970 strbuf_addf(&buf, "\n%c ", comment_line_char);
1971 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1972 ++opts->current_fixup_count + 1);
1973 strbuf_addstr(&buf, "\n\n");
1974 strbuf_add_commented_lines(&buf, body, strlen(body));
1975 } else
1976 return error(_("unknown command: %d"), command);
1977 unuse_commit_buffer(commit, message);
1979 if (!res)
1980 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1982 strbuf_release(&buf);
1984 if (!res) {
1985 strbuf_addf(&opts->current_fixups, "%s%s %s",
1986 opts->current_fixups.len ? "\n" : "",
1987 command_to_string(command),
1988 oid_to_hex(&commit->object.oid));
1989 res = write_message(opts->current_fixups.buf,
1990 opts->current_fixups.len,
1991 rebase_path_current_fixups(), 0);
1994 return res;
1997 static void flush_rewritten_pending(void)
1999 struct strbuf buf = STRBUF_INIT;
2000 struct object_id newoid;
2001 FILE *out;
2003 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2004 !get_oid("HEAD", &newoid) &&
2005 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2006 char *bol = buf.buf, *eol;
2008 while (*bol) {
2009 eol = strchrnul(bol, '\n');
2010 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2011 bol, oid_to_hex(&newoid));
2012 if (!*eol)
2013 break;
2014 bol = eol + 1;
2016 fclose(out);
2017 unlink(rebase_path_rewritten_pending());
2019 strbuf_release(&buf);
2022 static void record_in_rewritten(struct object_id *oid,
2023 enum todo_command next_command)
2025 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2027 if (!out)
2028 return;
2030 fprintf(out, "%s\n", oid_to_hex(oid));
2031 fclose(out);
2033 if (!is_fixup(next_command))
2034 flush_rewritten_pending();
2037 static int should_edit(struct replay_opts *opts) {
2038 if (opts->edit < 0)
2040 * Note that we only handle the case of non-conflicted
2041 * commits; continue_single_pick() handles the conflicted
2042 * commits itself instead of calling this function.
2044 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2045 return opts->edit;
2048 static int do_pick_commit(struct repository *r,
2049 struct todo_item *item,
2050 struct replay_opts *opts,
2051 int final_fixup, int *check_todo)
2053 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2054 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2055 struct object_id head;
2056 struct commit *base, *next, *parent;
2057 const char *base_label, *next_label;
2058 char *author = NULL;
2059 struct commit_message msg = { NULL, NULL, NULL, NULL };
2060 struct strbuf msgbuf = STRBUF_INIT;
2061 int res, unborn = 0, reword = 0, allow, drop_commit;
2062 enum todo_command command = item->command;
2063 struct commit *commit = item->commit;
2065 if (opts->no_commit) {
2067 * We do not intend to commit immediately. We just want to
2068 * merge the differences in, so let's compute the tree
2069 * that represents the "current" state for the merge machinery
2070 * to work on.
2072 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2073 return error(_("your index file is unmerged."));
2074 } else {
2075 unborn = get_oid("HEAD", &head);
2076 /* Do we want to generate a root commit? */
2077 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2078 oideq(&head, &opts->squash_onto)) {
2079 if (is_fixup(command))
2080 return error(_("cannot fixup root commit"));
2081 flags |= CREATE_ROOT_COMMIT;
2082 unborn = 1;
2083 } else if (unborn)
2084 oidcpy(&head, the_hash_algo->empty_tree);
2085 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2086 NULL, 0))
2087 return error_dirty_index(r, opts);
2089 discard_index(r->index);
2091 if (!commit->parents)
2092 parent = NULL;
2093 else if (commit->parents->next) {
2094 /* Reverting or cherry-picking a merge commit */
2095 int cnt;
2096 struct commit_list *p;
2098 if (!opts->mainline)
2099 return error(_("commit %s is a merge but no -m option was given."),
2100 oid_to_hex(&commit->object.oid));
2102 for (cnt = 1, p = commit->parents;
2103 cnt != opts->mainline && p;
2104 cnt++)
2105 p = p->next;
2106 if (cnt != opts->mainline || !p)
2107 return error(_("commit %s does not have parent %d"),
2108 oid_to_hex(&commit->object.oid), opts->mainline);
2109 parent = p->item;
2110 } else if (1 < opts->mainline)
2112 * Non-first parent explicitly specified as mainline for
2113 * non-merge commit
2115 return error(_("commit %s does not have parent %d"),
2116 oid_to_hex(&commit->object.oid), opts->mainline);
2117 else
2118 parent = commit->parents->item;
2120 if (get_message(commit, &msg) != 0)
2121 return error(_("cannot get commit message for %s"),
2122 oid_to_hex(&commit->object.oid));
2124 if (opts->allow_ff && !is_fixup(command) &&
2125 ((parent && oideq(&parent->object.oid, &head)) ||
2126 (!parent && unborn))) {
2127 if (is_rebase_i(opts))
2128 write_author_script(msg.message);
2129 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2130 opts);
2131 if (res || command != TODO_REWORD)
2132 goto leave;
2133 reword = 1;
2134 msg_file = NULL;
2135 goto fast_forward_edit;
2137 if (parent && parse_commit(parent) < 0)
2138 /* TRANSLATORS: The first %s will be a "todo" command like
2139 "revert" or "pick", the second %s a SHA1. */
2140 return error(_("%s: cannot parse parent commit %s"),
2141 command_to_string(command),
2142 oid_to_hex(&parent->object.oid));
2145 * "commit" is an existing commit. We would want to apply
2146 * the difference it introduces since its first parent "prev"
2147 * on top of the current HEAD if we are cherry-pick. Or the
2148 * reverse of it if we are revert.
2151 if (command == TODO_REVERT) {
2152 base = commit;
2153 base_label = msg.label;
2154 next = parent;
2155 next_label = msg.parent_label;
2156 strbuf_addstr(&msgbuf, "Revert \"");
2157 strbuf_addstr(&msgbuf, msg.subject);
2158 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2159 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2161 if (commit->parents && commit->parents->next) {
2162 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2163 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2165 strbuf_addstr(&msgbuf, ".\n");
2166 } else {
2167 const char *p;
2169 base = parent;
2170 base_label = msg.parent_label;
2171 next = commit;
2172 next_label = msg.label;
2174 /* Append the commit log message to msgbuf. */
2175 if (find_commit_subject(msg.message, &p))
2176 strbuf_addstr(&msgbuf, p);
2178 if (opts->record_origin) {
2179 strbuf_complete_line(&msgbuf);
2180 if (!has_conforming_footer(&msgbuf, NULL, 0))
2181 strbuf_addch(&msgbuf, '\n');
2182 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2183 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2184 strbuf_addstr(&msgbuf, ")\n");
2186 if (!is_fixup(command))
2187 author = get_author(msg.message);
2190 if (command == TODO_REWORD)
2191 reword = 1;
2192 else if (is_fixup(command)) {
2193 if (update_squash_messages(r, command, commit,
2194 opts, item->flags))
2195 return -1;
2196 flags |= AMEND_MSG;
2197 if (!final_fixup)
2198 msg_file = rebase_path_squash_msg();
2199 else if (file_exists(rebase_path_fixup_msg())) {
2200 flags |= VERBATIM_MSG;
2201 msg_file = rebase_path_fixup_msg();
2202 } else {
2203 const char *dest = git_path_squash_msg(r);
2204 unlink(dest);
2205 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2206 return error(_("could not rename '%s' to '%s'"),
2207 rebase_path_squash_msg(), dest);
2208 unlink(git_path_merge_msg(r));
2209 msg_file = dest;
2210 flags |= EDIT_MSG;
2214 if (opts->signoff && !is_fixup(command))
2215 append_signoff(&msgbuf, 0, 0);
2217 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2218 res = -1;
2219 else if (!opts->strategy ||
2220 !strcmp(opts->strategy, "recursive") ||
2221 !strcmp(opts->strategy, "ort") ||
2222 command == TODO_REVERT) {
2223 res = do_recursive_merge(r, base, next, base_label, next_label,
2224 &head, &msgbuf, opts);
2225 if (res < 0)
2226 goto leave;
2228 res |= write_message(msgbuf.buf, msgbuf.len,
2229 git_path_merge_msg(r), 0);
2230 } else {
2231 struct commit_list *common = NULL;
2232 struct commit_list *remotes = NULL;
2234 res = write_message(msgbuf.buf, msgbuf.len,
2235 git_path_merge_msg(r), 0);
2237 commit_list_insert(base, &common);
2238 commit_list_insert(next, &remotes);
2239 res |= try_merge_command(r, opts->strategy,
2240 opts->xopts_nr, (const char **)opts->xopts,
2241 common, oid_to_hex(&head), remotes);
2242 free_commit_list(common);
2243 free_commit_list(remotes);
2245 strbuf_release(&msgbuf);
2248 * If the merge was clean or if it failed due to conflict, we write
2249 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2250 * However, if the merge did not even start, then we don't want to
2251 * write it at all.
2253 if ((command == TODO_PICK || command == TODO_REWORD ||
2254 command == TODO_EDIT) && !opts->no_commit &&
2255 (res == 0 || res == 1) &&
2256 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2257 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2258 res = -1;
2259 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2260 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2261 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2262 res = -1;
2264 if (res) {
2265 error(command == TODO_REVERT
2266 ? _("could not revert %s... %s")
2267 : _("could not apply %s... %s"),
2268 short_commit_name(commit), msg.subject);
2269 print_advice(r, res == 1, opts);
2270 repo_rerere(r, opts->allow_rerere_auto);
2271 goto leave;
2274 drop_commit = 0;
2275 allow = allow_empty(r, opts, commit);
2276 if (allow < 0) {
2277 res = allow;
2278 goto leave;
2279 } else if (allow == 1) {
2280 flags |= ALLOW_EMPTY;
2281 } else if (allow == 2) {
2282 drop_commit = 1;
2283 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2284 NULL, 0);
2285 unlink(git_path_merge_msg(r));
2286 unlink(git_path_auto_merge(r));
2287 fprintf(stderr,
2288 _("dropping %s %s -- patch contents already upstream\n"),
2289 oid_to_hex(&commit->object.oid), msg.subject);
2290 } /* else allow == 0 and there's nothing special to do */
2291 if (!opts->no_commit && !drop_commit) {
2292 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2293 res = do_commit(r, msg_file, author, opts, flags,
2294 commit? &commit->object.oid : NULL);
2295 else
2296 res = error(_("unable to parse commit author"));
2297 *check_todo = !!(flags & EDIT_MSG);
2298 if (!res && reword) {
2299 fast_forward_edit:
2300 res = run_git_commit(NULL, opts, EDIT_MSG |
2301 VERIFY_MSG | AMEND_MSG |
2302 (flags & ALLOW_EMPTY));
2303 *check_todo = 1;
2308 if (!res && final_fixup) {
2309 unlink(rebase_path_fixup_msg());
2310 unlink(rebase_path_squash_msg());
2311 unlink(rebase_path_current_fixups());
2312 strbuf_reset(&opts->current_fixups);
2313 opts->current_fixup_count = 0;
2316 leave:
2317 free_message(commit, &msg);
2318 free(author);
2319 update_abort_safety_file();
2321 return res;
2324 static int prepare_revs(struct replay_opts *opts)
2327 * picking (but not reverting) ranges (but not individual revisions)
2328 * should be done in reverse
2330 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2331 opts->revs->reverse ^= 1;
2333 if (prepare_revision_walk(opts->revs))
2334 return error(_("revision walk setup failed"));
2336 return 0;
2339 static int read_and_refresh_cache(struct repository *r,
2340 struct replay_opts *opts)
2342 struct lock_file index_lock = LOCK_INIT;
2343 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2344 if (repo_read_index(r) < 0) {
2345 rollback_lock_file(&index_lock);
2346 return error(_("git %s: failed to read the index"),
2347 _(action_name(opts)));
2349 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2350 if (index_fd >= 0) {
2351 if (write_locked_index(r->index, &index_lock,
2352 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2353 return error(_("git %s: failed to refresh the index"),
2354 _(action_name(opts)));
2357 return 0;
2360 void todo_list_release(struct todo_list *todo_list)
2362 strbuf_release(&todo_list->buf);
2363 FREE_AND_NULL(todo_list->items);
2364 todo_list->nr = todo_list->alloc = 0;
2367 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2369 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2370 todo_list->total_nr++;
2371 return todo_list->items + todo_list->nr++;
2374 const char *todo_item_get_arg(struct todo_list *todo_list,
2375 struct todo_item *item)
2377 return todo_list->buf.buf + item->arg_offset;
2380 static int is_command(enum todo_command command, const char **bol)
2382 const char *str = todo_command_info[command].str;
2383 const char nick = todo_command_info[command].c;
2384 const char *p = *bol + 1;
2386 return skip_prefix(*bol, str, bol) ||
2387 ((nick && **bol == nick) &&
2388 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2389 (*bol = p));
2392 static int parse_insn_line(struct repository *r, struct todo_item *item,
2393 const char *buf, const char *bol, char *eol)
2395 struct object_id commit_oid;
2396 char *end_of_object_name;
2397 int i, saved, status, padding;
2399 item->flags = 0;
2401 /* left-trim */
2402 bol += strspn(bol, " \t");
2404 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2405 item->command = TODO_COMMENT;
2406 item->commit = NULL;
2407 item->arg_offset = bol - buf;
2408 item->arg_len = eol - bol;
2409 return 0;
2412 for (i = 0; i < TODO_COMMENT; i++)
2413 if (is_command(i, &bol)) {
2414 item->command = i;
2415 break;
2417 if (i >= TODO_COMMENT)
2418 return -1;
2420 /* Eat up extra spaces/ tabs before object name */
2421 padding = strspn(bol, " \t");
2422 bol += padding;
2424 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2425 if (bol != eol)
2426 return error(_("%s does not accept arguments: '%s'"),
2427 command_to_string(item->command), bol);
2428 item->commit = NULL;
2429 item->arg_offset = bol - buf;
2430 item->arg_len = eol - bol;
2431 return 0;
2434 if (!padding)
2435 return error(_("missing arguments for %s"),
2436 command_to_string(item->command));
2438 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2439 item->command == TODO_RESET) {
2440 item->commit = NULL;
2441 item->arg_offset = bol - buf;
2442 item->arg_len = (int)(eol - bol);
2443 return 0;
2446 if (item->command == TODO_FIXUP) {
2447 if (skip_prefix(bol, "-C", &bol) &&
2448 (*bol == ' ' || *bol == '\t')) {
2449 bol += strspn(bol, " \t");
2450 item->flags |= TODO_REPLACE_FIXUP_MSG;
2451 } else if (skip_prefix(bol, "-c", &bol) &&
2452 (*bol == ' ' || *bol == '\t')) {
2453 bol += strspn(bol, " \t");
2454 item->flags |= TODO_EDIT_FIXUP_MSG;
2458 if (item->command == TODO_MERGE) {
2459 if (skip_prefix(bol, "-C", &bol))
2460 bol += strspn(bol, " \t");
2461 else if (skip_prefix(bol, "-c", &bol)) {
2462 bol += strspn(bol, " \t");
2463 item->flags |= TODO_EDIT_MERGE_MSG;
2464 } else {
2465 item->flags |= TODO_EDIT_MERGE_MSG;
2466 item->commit = NULL;
2467 item->arg_offset = bol - buf;
2468 item->arg_len = (int)(eol - bol);
2469 return 0;
2473 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2474 saved = *end_of_object_name;
2475 *end_of_object_name = '\0';
2476 status = get_oid(bol, &commit_oid);
2477 if (status < 0)
2478 error(_("could not parse '%s'"), bol); /* return later */
2479 *end_of_object_name = saved;
2481 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2482 item->arg_offset = bol - buf;
2483 item->arg_len = (int)(eol - bol);
2485 if (status < 0)
2486 return status;
2488 item->commit = lookup_commit_reference(r, &commit_oid);
2489 return item->commit ? 0 : -1;
2492 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2494 const char *todo_file, *bol;
2495 struct strbuf buf = STRBUF_INIT;
2496 int ret = 0;
2498 todo_file = git_path_todo_file();
2499 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2500 if (errno == ENOENT || errno == ENOTDIR)
2501 return -1;
2502 else
2503 return error_errno("unable to open '%s'", todo_file);
2505 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2506 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2507 *action = REPLAY_PICK;
2508 else if (is_command(TODO_REVERT, &bol) &&
2509 (*bol == ' ' || *bol == '\t'))
2510 *action = REPLAY_REVERT;
2511 else
2512 ret = -1;
2514 strbuf_release(&buf);
2516 return ret;
2519 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2520 struct todo_list *todo_list)
2522 struct todo_item *item;
2523 char *p = buf, *next_p;
2524 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2526 todo_list->current = todo_list->nr = 0;
2528 for (i = 1; *p; i++, p = next_p) {
2529 char *eol = strchrnul(p, '\n');
2531 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2533 if (p != eol && eol[-1] == '\r')
2534 eol--; /* strip Carriage Return */
2536 item = append_new_todo(todo_list);
2537 item->offset_in_buf = p - todo_list->buf.buf;
2538 if (parse_insn_line(r, item, buf, p, eol)) {
2539 res = error(_("invalid line %d: %.*s"),
2540 i, (int)(eol - p), p);
2541 item->command = TODO_COMMENT + 1;
2542 item->arg_offset = p - buf;
2543 item->arg_len = (int)(eol - p);
2544 item->commit = NULL;
2547 if (fixup_okay)
2548 ; /* do nothing */
2549 else if (is_fixup(item->command))
2550 return error(_("cannot '%s' without a previous commit"),
2551 command_to_string(item->command));
2552 else if (!is_noop(item->command))
2553 fixup_okay = 1;
2556 return res;
2559 static int count_commands(struct todo_list *todo_list)
2561 int count = 0, i;
2563 for (i = 0; i < todo_list->nr; i++)
2564 if (todo_list->items[i].command != TODO_COMMENT)
2565 count++;
2567 return count;
2570 static int get_item_line_offset(struct todo_list *todo_list, int index)
2572 return index < todo_list->nr ?
2573 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2576 static const char *get_item_line(struct todo_list *todo_list, int index)
2578 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2581 static int get_item_line_length(struct todo_list *todo_list, int index)
2583 return get_item_line_offset(todo_list, index + 1)
2584 - get_item_line_offset(todo_list, index);
2587 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2589 int fd;
2590 ssize_t len;
2592 fd = open(path, O_RDONLY);
2593 if (fd < 0)
2594 return error_errno(_("could not open '%s'"), path);
2595 len = strbuf_read(sb, fd, 0);
2596 close(fd);
2597 if (len < 0)
2598 return error(_("could not read '%s'."), path);
2599 return len;
2602 static int have_finished_the_last_pick(void)
2604 struct strbuf buf = STRBUF_INIT;
2605 const char *eol;
2606 const char *todo_path = git_path_todo_file();
2607 int ret = 0;
2609 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2610 if (errno == ENOENT) {
2611 return 0;
2612 } else {
2613 error_errno("unable to open '%s'", todo_path);
2614 return 0;
2617 /* If there is only one line then we are done */
2618 eol = strchr(buf.buf, '\n');
2619 if (!eol || !eol[1])
2620 ret = 1;
2622 strbuf_release(&buf);
2624 return ret;
2627 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2629 struct replay_opts opts = REPLAY_OPTS_INIT;
2630 int need_cleanup = 0;
2632 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2633 if (!refs_delete_ref(get_main_ref_store(r), "",
2634 "CHERRY_PICK_HEAD", NULL, 0) &&
2635 verbose)
2636 warning(_("cancelling a cherry picking in progress"));
2637 opts.action = REPLAY_PICK;
2638 need_cleanup = 1;
2641 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2642 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2643 NULL, 0) &&
2644 verbose)
2645 warning(_("cancelling a revert in progress"));
2646 opts.action = REPLAY_REVERT;
2647 need_cleanup = 1;
2650 unlink(git_path_auto_merge(r));
2652 if (!need_cleanup)
2653 return;
2655 if (!have_finished_the_last_pick())
2656 return;
2658 sequencer_remove_state(&opts);
2661 static void todo_list_write_total_nr(struct todo_list *todo_list)
2663 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2665 if (f) {
2666 fprintf(f, "%d\n", todo_list->total_nr);
2667 fclose(f);
2671 static int read_populate_todo(struct repository *r,
2672 struct todo_list *todo_list,
2673 struct replay_opts *opts)
2675 struct stat st;
2676 const char *todo_file = get_todo_path(opts);
2677 int res;
2679 strbuf_reset(&todo_list->buf);
2680 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2681 return -1;
2683 res = stat(todo_file, &st);
2684 if (res)
2685 return error(_("could not stat '%s'"), todo_file);
2686 fill_stat_data(&todo_list->stat, &st);
2688 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2689 if (res) {
2690 if (is_rebase_i(opts))
2691 return error(_("please fix this using "
2692 "'git rebase --edit-todo'."));
2693 return error(_("unusable instruction sheet: '%s'"), todo_file);
2696 if (!todo_list->nr &&
2697 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2698 return error(_("no commits parsed."));
2700 if (!is_rebase_i(opts)) {
2701 enum todo_command valid =
2702 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2703 int i;
2705 for (i = 0; i < todo_list->nr; i++)
2706 if (valid == todo_list->items[i].command)
2707 continue;
2708 else if (valid == TODO_PICK)
2709 return error(_("cannot cherry-pick during a revert."));
2710 else
2711 return error(_("cannot revert during a cherry-pick."));
2714 if (is_rebase_i(opts)) {
2715 struct todo_list done = TODO_LIST_INIT;
2717 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2718 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2719 todo_list->done_nr = count_commands(&done);
2720 else
2721 todo_list->done_nr = 0;
2723 todo_list->total_nr = todo_list->done_nr
2724 + count_commands(todo_list);
2725 todo_list_release(&done);
2727 todo_list_write_total_nr(todo_list);
2730 return 0;
2733 static int git_config_string_dup(char **dest,
2734 const char *var, const char *value)
2736 if (!value)
2737 return config_error_nonbool(var);
2738 free(*dest);
2739 *dest = xstrdup(value);
2740 return 0;
2743 static int populate_opts_cb(const char *key, const char *value, void *data)
2745 struct replay_opts *opts = data;
2746 int error_flag = 1;
2748 if (!value)
2749 error_flag = 0;
2750 else if (!strcmp(key, "options.no-commit"))
2751 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2752 else if (!strcmp(key, "options.edit"))
2753 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2754 else if (!strcmp(key, "options.allow-empty"))
2755 opts->allow_empty =
2756 git_config_bool_or_int(key, value, &error_flag);
2757 else if (!strcmp(key, "options.allow-empty-message"))
2758 opts->allow_empty_message =
2759 git_config_bool_or_int(key, value, &error_flag);
2760 else if (!strcmp(key, "options.keep-redundant-commits"))
2761 opts->keep_redundant_commits =
2762 git_config_bool_or_int(key, value, &error_flag);
2763 else if (!strcmp(key, "options.signoff"))
2764 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2765 else if (!strcmp(key, "options.record-origin"))
2766 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2767 else if (!strcmp(key, "options.allow-ff"))
2768 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2769 else if (!strcmp(key, "options.mainline"))
2770 opts->mainline = git_config_int(key, value);
2771 else if (!strcmp(key, "options.strategy"))
2772 git_config_string_dup(&opts->strategy, key, value);
2773 else if (!strcmp(key, "options.gpg-sign"))
2774 git_config_string_dup(&opts->gpg_sign, key, value);
2775 else if (!strcmp(key, "options.strategy-option")) {
2776 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2777 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2778 } else if (!strcmp(key, "options.allow-rerere-auto"))
2779 opts->allow_rerere_auto =
2780 git_config_bool_or_int(key, value, &error_flag) ?
2781 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2782 else if (!strcmp(key, "options.default-msg-cleanup")) {
2783 opts->explicit_cleanup = 1;
2784 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2785 } else
2786 return error(_("invalid key: %s"), key);
2788 if (!error_flag)
2789 return error(_("invalid value for %s: %s"), key, value);
2791 return 0;
2794 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2796 int i;
2797 char *strategy_opts_string = raw_opts;
2799 if (*strategy_opts_string == ' ')
2800 strategy_opts_string++;
2802 opts->xopts_nr = split_cmdline(strategy_opts_string,
2803 (const char ***)&opts->xopts);
2804 for (i = 0; i < opts->xopts_nr; i++) {
2805 const char *arg = opts->xopts[i];
2807 skip_prefix(arg, "--", &arg);
2808 opts->xopts[i] = xstrdup(arg);
2812 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2814 strbuf_reset(buf);
2815 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2816 return;
2817 opts->strategy = strbuf_detach(buf, NULL);
2818 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2819 return;
2821 parse_strategy_opts(opts, buf->buf);
2824 static int read_populate_opts(struct replay_opts *opts)
2826 if (is_rebase_i(opts)) {
2827 struct strbuf buf = STRBUF_INIT;
2828 int ret = 0;
2830 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2831 READ_ONELINER_SKIP_IF_EMPTY)) {
2832 if (!starts_with(buf.buf, "-S"))
2833 strbuf_reset(&buf);
2834 else {
2835 free(opts->gpg_sign);
2836 opts->gpg_sign = xstrdup(buf.buf + 2);
2838 strbuf_reset(&buf);
2841 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2842 READ_ONELINER_SKIP_IF_EMPTY)) {
2843 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2844 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2845 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2846 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2847 strbuf_reset(&buf);
2850 if (file_exists(rebase_path_verbose()))
2851 opts->verbose = 1;
2853 if (file_exists(rebase_path_quiet()))
2854 opts->quiet = 1;
2856 if (file_exists(rebase_path_signoff())) {
2857 opts->allow_ff = 0;
2858 opts->signoff = 1;
2861 if (file_exists(rebase_path_cdate_is_adate())) {
2862 opts->allow_ff = 0;
2863 opts->committer_date_is_author_date = 1;
2866 if (file_exists(rebase_path_ignore_date())) {
2867 opts->allow_ff = 0;
2868 opts->ignore_date = 1;
2871 if (file_exists(rebase_path_reschedule_failed_exec()))
2872 opts->reschedule_failed_exec = 1;
2873 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2874 opts->reschedule_failed_exec = 0;
2876 if (file_exists(rebase_path_drop_redundant_commits()))
2877 opts->drop_redundant_commits = 1;
2879 if (file_exists(rebase_path_keep_redundant_commits()))
2880 opts->keep_redundant_commits = 1;
2882 read_strategy_opts(opts, &buf);
2883 strbuf_reset(&buf);
2885 if (read_oneliner(&opts->current_fixups,
2886 rebase_path_current_fixups(),
2887 READ_ONELINER_SKIP_IF_EMPTY)) {
2888 const char *p = opts->current_fixups.buf;
2889 opts->current_fixup_count = 1;
2890 while ((p = strchr(p, '\n'))) {
2891 opts->current_fixup_count++;
2892 p++;
2896 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2897 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2898 ret = error(_("unusable squash-onto"));
2899 goto done_rebase_i;
2901 opts->have_squash_onto = 1;
2904 done_rebase_i:
2905 strbuf_release(&buf);
2906 return ret;
2909 if (!file_exists(git_path_opts_file()))
2910 return 0;
2912 * The function git_parse_source(), called from git_config_from_file(),
2913 * may die() in case of a syntactically incorrect file. We do not care
2914 * about this case, though, because we wrote that file ourselves, so we
2915 * are pretty certain that it is syntactically correct.
2917 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2918 return error(_("malformed options sheet: '%s'"),
2919 git_path_opts_file());
2920 return 0;
2923 static void write_strategy_opts(struct replay_opts *opts)
2925 int i;
2926 struct strbuf buf = STRBUF_INIT;
2928 for (i = 0; i < opts->xopts_nr; ++i)
2929 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2931 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2932 strbuf_release(&buf);
2935 int write_basic_state(struct replay_opts *opts, const char *head_name,
2936 struct commit *onto, const struct object_id *orig_head)
2938 if (head_name)
2939 write_file(rebase_path_head_name(), "%s\n", head_name);
2940 if (onto)
2941 write_file(rebase_path_onto(), "%s\n",
2942 oid_to_hex(&onto->object.oid));
2943 if (orig_head)
2944 write_file(rebase_path_orig_head(), "%s\n",
2945 oid_to_hex(orig_head));
2947 if (opts->quiet)
2948 write_file(rebase_path_quiet(), "%s", "");
2949 if (opts->verbose)
2950 write_file(rebase_path_verbose(), "%s", "");
2951 if (opts->strategy)
2952 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2953 if (opts->xopts_nr > 0)
2954 write_strategy_opts(opts);
2956 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2957 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2958 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2959 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2961 if (opts->gpg_sign)
2962 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2963 if (opts->signoff)
2964 write_file(rebase_path_signoff(), "--signoff\n");
2965 if (opts->drop_redundant_commits)
2966 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2967 if (opts->keep_redundant_commits)
2968 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2969 if (opts->committer_date_is_author_date)
2970 write_file(rebase_path_cdate_is_adate(), "%s", "");
2971 if (opts->ignore_date)
2972 write_file(rebase_path_ignore_date(), "%s", "");
2973 if (opts->reschedule_failed_exec)
2974 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2975 else
2976 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2978 return 0;
2981 static int walk_revs_populate_todo(struct todo_list *todo_list,
2982 struct replay_opts *opts)
2984 enum todo_command command = opts->action == REPLAY_PICK ?
2985 TODO_PICK : TODO_REVERT;
2986 const char *command_string = todo_command_info[command].str;
2987 const char *encoding;
2988 struct commit *commit;
2990 if (prepare_revs(opts))
2991 return -1;
2993 encoding = get_log_output_encoding();
2995 while ((commit = get_revision(opts->revs))) {
2996 struct todo_item *item = append_new_todo(todo_list);
2997 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2998 const char *subject;
2999 int subject_len;
3001 item->command = command;
3002 item->commit = commit;
3003 item->arg_offset = 0;
3004 item->arg_len = 0;
3005 item->offset_in_buf = todo_list->buf.len;
3006 subject_len = find_commit_subject(commit_buffer, &subject);
3007 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3008 short_commit_name(commit), subject_len, subject);
3009 unuse_commit_buffer(commit, commit_buffer);
3012 if (!todo_list->nr)
3013 return error(_("empty commit set passed"));
3015 return 0;
3018 static int create_seq_dir(struct repository *r)
3020 enum replay_action action;
3021 const char *in_progress_error = NULL;
3022 const char *in_progress_advice = NULL;
3023 unsigned int advise_skip =
3024 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3025 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3027 if (!sequencer_get_last_command(r, &action)) {
3028 switch (action) {
3029 case REPLAY_REVERT:
3030 in_progress_error = _("revert is already in progress");
3031 in_progress_advice =
3032 _("try \"git revert (--continue | %s--abort | --quit)\"");
3033 break;
3034 case REPLAY_PICK:
3035 in_progress_error = _("cherry-pick is already in progress");
3036 in_progress_advice =
3037 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3038 break;
3039 default:
3040 BUG("unexpected action in create_seq_dir");
3043 if (in_progress_error) {
3044 error("%s", in_progress_error);
3045 if (advice_sequencer_in_use)
3046 advise(in_progress_advice,
3047 advise_skip ? "--skip | " : "");
3048 return -1;
3050 if (mkdir(git_path_seq_dir(), 0777) < 0)
3051 return error_errno(_("could not create sequencer directory '%s'"),
3052 git_path_seq_dir());
3054 return 0;
3057 static int save_head(const char *head)
3059 struct lock_file head_lock = LOCK_INIT;
3060 struct strbuf buf = STRBUF_INIT;
3061 int fd;
3062 ssize_t written;
3064 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3065 if (fd < 0)
3066 return error_errno(_("could not lock HEAD"));
3067 strbuf_addf(&buf, "%s\n", head);
3068 written = write_in_full(fd, buf.buf, buf.len);
3069 strbuf_release(&buf);
3070 if (written < 0) {
3071 error_errno(_("could not write to '%s'"), git_path_head_file());
3072 rollback_lock_file(&head_lock);
3073 return -1;
3075 if (commit_lock_file(&head_lock) < 0)
3076 return error(_("failed to finalize '%s'"), git_path_head_file());
3077 return 0;
3080 static int rollback_is_safe(void)
3082 struct strbuf sb = STRBUF_INIT;
3083 struct object_id expected_head, actual_head;
3085 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3086 strbuf_trim(&sb);
3087 if (get_oid_hex(sb.buf, &expected_head)) {
3088 strbuf_release(&sb);
3089 die(_("could not parse %s"), git_path_abort_safety_file());
3091 strbuf_release(&sb);
3093 else if (errno == ENOENT)
3094 oidclr(&expected_head);
3095 else
3096 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3098 if (get_oid("HEAD", &actual_head))
3099 oidclr(&actual_head);
3101 return oideq(&actual_head, &expected_head);
3104 static int reset_merge(const struct object_id *oid)
3106 int ret;
3107 struct strvec argv = STRVEC_INIT;
3109 strvec_pushl(&argv, "reset", "--merge", NULL);
3111 if (!is_null_oid(oid))
3112 strvec_push(&argv, oid_to_hex(oid));
3114 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3115 strvec_clear(&argv);
3117 return ret;
3120 static int rollback_single_pick(struct repository *r)
3122 struct object_id head_oid;
3124 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3125 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3126 return error(_("no cherry-pick or revert in progress"));
3127 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3128 return error(_("cannot resolve HEAD"));
3129 if (is_null_oid(&head_oid))
3130 return error(_("cannot abort from a branch yet to be born"));
3131 return reset_merge(&head_oid);
3134 static int skip_single_pick(void)
3136 struct object_id head;
3138 if (read_ref_full("HEAD", 0, &head, NULL))
3139 return error(_("cannot resolve HEAD"));
3140 return reset_merge(&head);
3143 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3145 FILE *f;
3146 struct object_id oid;
3147 struct strbuf buf = STRBUF_INIT;
3148 const char *p;
3150 f = fopen(git_path_head_file(), "r");
3151 if (!f && errno == ENOENT) {
3153 * There is no multiple-cherry-pick in progress.
3154 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3155 * a single-cherry-pick in progress, abort that.
3157 return rollback_single_pick(r);
3159 if (!f)
3160 return error_errno(_("cannot open '%s'"), git_path_head_file());
3161 if (strbuf_getline_lf(&buf, f)) {
3162 error(_("cannot read '%s': %s"), git_path_head_file(),
3163 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3164 fclose(f);
3165 goto fail;
3167 fclose(f);
3168 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3169 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3170 git_path_head_file());
3171 goto fail;
3173 if (is_null_oid(&oid)) {
3174 error(_("cannot abort from a branch yet to be born"));
3175 goto fail;
3178 if (!rollback_is_safe()) {
3179 /* Do not error, just do not rollback */
3180 warning(_("You seem to have moved HEAD. "
3181 "Not rewinding, check your HEAD!"));
3182 } else
3183 if (reset_merge(&oid))
3184 goto fail;
3185 strbuf_release(&buf);
3186 return sequencer_remove_state(opts);
3187 fail:
3188 strbuf_release(&buf);
3189 return -1;
3192 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3194 enum replay_action action = -1;
3195 sequencer_get_last_command(r, &action);
3198 * Check whether the subcommand requested to skip the commit is actually
3199 * in progress and that it's safe to skip the commit.
3201 * opts->action tells us which subcommand requested to skip the commit.
3202 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3203 * action is in progress and we can skip the commit.
3205 * Otherwise we check that the last instruction was related to the
3206 * particular subcommand we're trying to execute and barf if that's not
3207 * the case.
3209 * Finally we check that the rollback is "safe", i.e., has the HEAD
3210 * moved? In this case, it doesn't make sense to "reset the merge" and
3211 * "skip the commit" as the user already handled this by committing. But
3212 * we'd not want to barf here, instead give advice on how to proceed. We
3213 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3214 * it gets removed when the user commits, so if it still exists we're
3215 * sure the user can't have committed before.
3217 switch (opts->action) {
3218 case REPLAY_REVERT:
3219 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3220 if (action != REPLAY_REVERT)
3221 return error(_("no revert in progress"));
3222 if (!rollback_is_safe())
3223 goto give_advice;
3225 break;
3226 case REPLAY_PICK:
3227 if (!refs_ref_exists(get_main_ref_store(r),
3228 "CHERRY_PICK_HEAD")) {
3229 if (action != REPLAY_PICK)
3230 return error(_("no cherry-pick in progress"));
3231 if (!rollback_is_safe())
3232 goto give_advice;
3234 break;
3235 default:
3236 BUG("unexpected action in sequencer_skip");
3239 if (skip_single_pick())
3240 return error(_("failed to skip the commit"));
3241 if (!is_directory(git_path_seq_dir()))
3242 return 0;
3244 return sequencer_continue(r, opts);
3246 give_advice:
3247 error(_("there is nothing to skip"));
3249 if (advice_resolve_conflict) {
3250 advise(_("have you committed already?\n"
3251 "try \"git %s --continue\""),
3252 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3254 return -1;
3257 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3259 struct lock_file todo_lock = LOCK_INIT;
3260 const char *todo_path = get_todo_path(opts);
3261 int next = todo_list->current, offset, fd;
3264 * rebase -i writes "git-rebase-todo" without the currently executing
3265 * command, appending it to "done" instead.
3267 if (is_rebase_i(opts))
3268 next++;
3270 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3271 if (fd < 0)
3272 return error_errno(_("could not lock '%s'"), todo_path);
3273 offset = get_item_line_offset(todo_list, next);
3274 if (write_in_full(fd, todo_list->buf.buf + offset,
3275 todo_list->buf.len - offset) < 0)
3276 return error_errno(_("could not write to '%s'"), todo_path);
3277 if (commit_lock_file(&todo_lock) < 0)
3278 return error(_("failed to finalize '%s'"), todo_path);
3280 if (is_rebase_i(opts) && next > 0) {
3281 const char *done = rebase_path_done();
3282 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3283 int ret = 0;
3285 if (fd < 0)
3286 return 0;
3287 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3288 get_item_line_length(todo_list, next - 1))
3289 < 0)
3290 ret = error_errno(_("could not write to '%s'"), done);
3291 if (close(fd) < 0)
3292 ret = error_errno(_("failed to finalize '%s'"), done);
3293 return ret;
3295 return 0;
3298 static int save_opts(struct replay_opts *opts)
3300 const char *opts_file = git_path_opts_file();
3301 int res = 0;
3303 if (opts->no_commit)
3304 res |= git_config_set_in_file_gently(opts_file,
3305 "options.no-commit", "true");
3306 if (opts->edit >= 0)
3307 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3308 opts->edit ? "true" : "false");
3309 if (opts->allow_empty)
3310 res |= git_config_set_in_file_gently(opts_file,
3311 "options.allow-empty", "true");
3312 if (opts->allow_empty_message)
3313 res |= git_config_set_in_file_gently(opts_file,
3314 "options.allow-empty-message", "true");
3315 if (opts->keep_redundant_commits)
3316 res |= git_config_set_in_file_gently(opts_file,
3317 "options.keep-redundant-commits", "true");
3318 if (opts->signoff)
3319 res |= git_config_set_in_file_gently(opts_file,
3320 "options.signoff", "true");
3321 if (opts->record_origin)
3322 res |= git_config_set_in_file_gently(opts_file,
3323 "options.record-origin", "true");
3324 if (opts->allow_ff)
3325 res |= git_config_set_in_file_gently(opts_file,
3326 "options.allow-ff", "true");
3327 if (opts->mainline) {
3328 struct strbuf buf = STRBUF_INIT;
3329 strbuf_addf(&buf, "%d", opts->mainline);
3330 res |= git_config_set_in_file_gently(opts_file,
3331 "options.mainline", buf.buf);
3332 strbuf_release(&buf);
3334 if (opts->strategy)
3335 res |= git_config_set_in_file_gently(opts_file,
3336 "options.strategy", opts->strategy);
3337 if (opts->gpg_sign)
3338 res |= git_config_set_in_file_gently(opts_file,
3339 "options.gpg-sign", opts->gpg_sign);
3340 if (opts->xopts) {
3341 int i;
3342 for (i = 0; i < opts->xopts_nr; i++)
3343 res |= git_config_set_multivar_in_file_gently(opts_file,
3344 "options.strategy-option",
3345 opts->xopts[i], "^$", 0);
3347 if (opts->allow_rerere_auto)
3348 res |= git_config_set_in_file_gently(opts_file,
3349 "options.allow-rerere-auto",
3350 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3351 "true" : "false");
3353 if (opts->explicit_cleanup)
3354 res |= git_config_set_in_file_gently(opts_file,
3355 "options.default-msg-cleanup",
3356 describe_cleanup_mode(opts->default_msg_cleanup));
3357 return res;
3360 static int make_patch(struct repository *r,
3361 struct commit *commit,
3362 struct replay_opts *opts)
3364 struct strbuf buf = STRBUF_INIT;
3365 struct rev_info log_tree_opt;
3366 const char *subject;
3367 char hex[GIT_MAX_HEXSZ + 1];
3368 int res = 0;
3370 oid_to_hex_r(hex, &commit->object.oid);
3371 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3372 return -1;
3373 res |= write_rebase_head(&commit->object.oid);
3375 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3376 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3377 repo_init_revisions(r, &log_tree_opt, NULL);
3378 log_tree_opt.abbrev = 0;
3379 log_tree_opt.diff = 1;
3380 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3381 log_tree_opt.disable_stdin = 1;
3382 log_tree_opt.no_commit_id = 1;
3383 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3384 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3385 if (!log_tree_opt.diffopt.file)
3386 res |= error_errno(_("could not open '%s'"), buf.buf);
3387 else {
3388 res |= log_tree_commit(&log_tree_opt, commit);
3389 fclose(log_tree_opt.diffopt.file);
3391 strbuf_reset(&buf);
3393 strbuf_addf(&buf, "%s/message", get_dir(opts));
3394 if (!file_exists(buf.buf)) {
3395 const char *encoding = get_commit_output_encoding();
3396 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3397 find_commit_subject(commit_buffer, &subject);
3398 res |= write_message(subject, strlen(subject), buf.buf, 1);
3399 unuse_commit_buffer(commit, commit_buffer);
3401 strbuf_release(&buf);
3403 return res;
3406 static int intend_to_amend(void)
3408 struct object_id head;
3409 char *p;
3411 if (get_oid("HEAD", &head))
3412 return error(_("cannot read HEAD"));
3414 p = oid_to_hex(&head);
3415 return write_message(p, strlen(p), rebase_path_amend(), 1);
3418 static int error_with_patch(struct repository *r,
3419 struct commit *commit,
3420 const char *subject, int subject_len,
3421 struct replay_opts *opts,
3422 int exit_code, int to_amend)
3424 if (commit) {
3425 if (make_patch(r, commit, opts))
3426 return -1;
3427 } else if (copy_file(rebase_path_message(),
3428 git_path_merge_msg(r), 0666))
3429 return error(_("unable to copy '%s' to '%s'"),
3430 git_path_merge_msg(r), rebase_path_message());
3432 if (to_amend) {
3433 if (intend_to_amend())
3434 return -1;
3436 fprintf(stderr,
3437 _("You can amend the commit now, with\n"
3438 "\n"
3439 " git commit --amend %s\n"
3440 "\n"
3441 "Once you are satisfied with your changes, run\n"
3442 "\n"
3443 " git rebase --continue\n"),
3444 gpg_sign_opt_quoted(opts));
3445 } else if (exit_code) {
3446 if (commit)
3447 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3448 short_commit_name(commit), subject_len, subject);
3449 else
3451 * We don't have the hash of the parent so
3452 * just print the line from the todo file.
3454 fprintf_ln(stderr, _("Could not merge %.*s"),
3455 subject_len, subject);
3458 return exit_code;
3461 static int error_failed_squash(struct repository *r,
3462 struct commit *commit,
3463 struct replay_opts *opts,
3464 int subject_len,
3465 const char *subject)
3467 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3468 return error(_("could not copy '%s' to '%s'"),
3469 rebase_path_squash_msg(), rebase_path_message());
3470 unlink(git_path_merge_msg(r));
3471 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3472 return error(_("could not copy '%s' to '%s'"),
3473 rebase_path_message(),
3474 git_path_merge_msg(r));
3475 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3478 static int do_exec(struct repository *r, const char *command_line)
3480 struct strvec child_env = STRVEC_INIT;
3481 const char *child_argv[] = { NULL, NULL };
3482 int dirty, status;
3484 fprintf(stderr, _("Executing: %s\n"), command_line);
3485 child_argv[0] = command_line;
3486 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3487 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3488 absolute_path(get_git_work_tree()));
3489 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3490 child_env.v);
3492 /* force re-reading of the cache */
3493 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3494 return error(_("could not read index"));
3496 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3498 if (status) {
3499 warning(_("execution failed: %s\n%s"
3500 "You can fix the problem, and then run\n"
3501 "\n"
3502 " git rebase --continue\n"
3503 "\n"),
3504 command_line,
3505 dirty ? N_("and made changes to the index and/or the "
3506 "working tree\n") : "");
3507 if (status == 127)
3508 /* command not found */
3509 status = 1;
3510 } else if (dirty) {
3511 warning(_("execution succeeded: %s\nbut "
3512 "left changes to the index and/or the working tree\n"
3513 "Commit or stash your changes, and then run\n"
3514 "\n"
3515 " git rebase --continue\n"
3516 "\n"), command_line);
3517 status = 1;
3520 strvec_clear(&child_env);
3522 return status;
3525 __attribute__((format (printf, 2, 3)))
3526 static int safe_append(const char *filename, const char *fmt, ...)
3528 va_list ap;
3529 struct lock_file lock = LOCK_INIT;
3530 int fd = hold_lock_file_for_update(&lock, filename,
3531 LOCK_REPORT_ON_ERROR);
3532 struct strbuf buf = STRBUF_INIT;
3534 if (fd < 0)
3535 return -1;
3537 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3538 error_errno(_("could not read '%s'"), filename);
3539 rollback_lock_file(&lock);
3540 return -1;
3542 strbuf_complete(&buf, '\n');
3543 va_start(ap, fmt);
3544 strbuf_vaddf(&buf, fmt, ap);
3545 va_end(ap);
3547 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3548 error_errno(_("could not write to '%s'"), filename);
3549 strbuf_release(&buf);
3550 rollback_lock_file(&lock);
3551 return -1;
3553 if (commit_lock_file(&lock) < 0) {
3554 strbuf_release(&buf);
3555 rollback_lock_file(&lock);
3556 return error(_("failed to finalize '%s'"), filename);
3559 strbuf_release(&buf);
3560 return 0;
3563 static int do_label(struct repository *r, const char *name, int len)
3565 struct ref_store *refs = get_main_ref_store(r);
3566 struct ref_transaction *transaction;
3567 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3568 struct strbuf msg = STRBUF_INIT;
3569 int ret = 0;
3570 struct object_id head_oid;
3572 if (len == 1 && *name == '#')
3573 return error(_("illegal label name: '%.*s'"), len, name);
3575 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3576 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3578 transaction = ref_store_transaction_begin(refs, &err);
3579 if (!transaction) {
3580 error("%s", err.buf);
3581 ret = -1;
3582 } else if (get_oid("HEAD", &head_oid)) {
3583 error(_("could not read HEAD"));
3584 ret = -1;
3585 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3586 NULL, 0, msg.buf, &err) < 0 ||
3587 ref_transaction_commit(transaction, &err)) {
3588 error("%s", err.buf);
3589 ret = -1;
3591 ref_transaction_free(transaction);
3592 strbuf_release(&err);
3593 strbuf_release(&msg);
3595 if (!ret)
3596 ret = safe_append(rebase_path_refs_to_delete(),
3597 "%s\n", ref_name.buf);
3598 strbuf_release(&ref_name);
3600 return ret;
3603 __attribute__((format (printf, 3, 4)))
3604 static const char *reflog_message(struct replay_opts *opts,
3605 const char *sub_action, const char *fmt, ...)
3607 va_list ap;
3608 static struct strbuf buf = STRBUF_INIT;
3609 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3611 va_start(ap, fmt);
3612 strbuf_reset(&buf);
3613 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3614 if (sub_action)
3615 strbuf_addf(&buf, " (%s)", sub_action);
3616 if (fmt) {
3617 strbuf_addstr(&buf, ": ");
3618 strbuf_vaddf(&buf, fmt, ap);
3620 va_end(ap);
3622 return buf.buf;
3625 static int do_reset(struct repository *r,
3626 const char *name, int len,
3627 struct replay_opts *opts)
3629 struct strbuf ref_name = STRBUF_INIT;
3630 struct object_id oid;
3631 struct lock_file lock = LOCK_INIT;
3632 struct tree_desc desc;
3633 struct tree *tree;
3634 struct unpack_trees_options unpack_tree_opts;
3635 int ret = 0;
3637 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3638 return -1;
3640 if (len == 10 && !strncmp("[new root]", name, len)) {
3641 if (!opts->have_squash_onto) {
3642 const char *hex;
3643 if (commit_tree("", 0, the_hash_algo->empty_tree,
3644 NULL, &opts->squash_onto,
3645 NULL, NULL))
3646 return error(_("writing fake root commit"));
3647 opts->have_squash_onto = 1;
3648 hex = oid_to_hex(&opts->squash_onto);
3649 if (write_message(hex, strlen(hex),
3650 rebase_path_squash_onto(), 0))
3651 return error(_("writing squash-onto"));
3653 oidcpy(&oid, &opts->squash_onto);
3654 } else {
3655 int i;
3657 /* Determine the length of the label */
3658 for (i = 0; i < len; i++)
3659 if (isspace(name[i]))
3660 break;
3661 len = i;
3663 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3664 if (get_oid(ref_name.buf, &oid) &&
3665 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3666 error(_("could not read '%s'"), ref_name.buf);
3667 rollback_lock_file(&lock);
3668 strbuf_release(&ref_name);
3669 return -1;
3673 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3674 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3675 unpack_tree_opts.head_idx = 1;
3676 unpack_tree_opts.src_index = r->index;
3677 unpack_tree_opts.dst_index = r->index;
3678 unpack_tree_opts.fn = oneway_merge;
3679 unpack_tree_opts.merge = 1;
3680 unpack_tree_opts.update = 1;
3681 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3683 if (repo_read_index_unmerged(r)) {
3684 rollback_lock_file(&lock);
3685 strbuf_release(&ref_name);
3686 return error_resolve_conflict(_(action_name(opts)));
3689 if (!fill_tree_descriptor(r, &desc, &oid)) {
3690 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3691 rollback_lock_file(&lock);
3692 free((void *)desc.buffer);
3693 strbuf_release(&ref_name);
3694 return -1;
3697 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3698 rollback_lock_file(&lock);
3699 free((void *)desc.buffer);
3700 strbuf_release(&ref_name);
3701 return -1;
3704 tree = parse_tree_indirect(&oid);
3705 prime_cache_tree(r, r->index, tree);
3707 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3708 ret = error(_("could not write index"));
3709 free((void *)desc.buffer);
3711 if (!ret)
3712 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3713 len, name), "HEAD", &oid,
3714 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3716 strbuf_release(&ref_name);
3717 return ret;
3720 static struct commit *lookup_label(const char *label, int len,
3721 struct strbuf *buf)
3723 struct commit *commit;
3725 strbuf_reset(buf);
3726 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3727 commit = lookup_commit_reference_by_name(buf->buf);
3728 if (!commit) {
3729 /* fall back to non-rewritten ref or commit */
3730 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3731 commit = lookup_commit_reference_by_name(buf->buf);
3734 if (!commit)
3735 error(_("could not resolve '%s'"), buf->buf);
3737 return commit;
3740 static int do_merge(struct repository *r,
3741 struct commit *commit,
3742 const char *arg, int arg_len,
3743 int flags, int *check_todo, struct replay_opts *opts)
3745 int run_commit_flags = 0;
3746 struct strbuf ref_name = STRBUF_INIT;
3747 struct commit *head_commit, *merge_commit, *i;
3748 struct commit_list *bases, *j, *reversed = NULL;
3749 struct commit_list *to_merge = NULL, **tail = &to_merge;
3750 const char *strategy = !opts->xopts_nr &&
3751 (!opts->strategy ||
3752 !strcmp(opts->strategy, "recursive") ||
3753 !strcmp(opts->strategy, "ort")) ?
3754 NULL : opts->strategy;
3755 struct merge_options o;
3756 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3757 static struct lock_file lock;
3758 const char *p;
3760 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3761 ret = -1;
3762 goto leave_merge;
3765 head_commit = lookup_commit_reference_by_name("HEAD");
3766 if (!head_commit) {
3767 ret = error(_("cannot merge without a current revision"));
3768 goto leave_merge;
3772 * For octopus merges, the arg starts with the list of revisions to be
3773 * merged. The list is optionally followed by '#' and the oneline.
3775 merge_arg_len = oneline_offset = arg_len;
3776 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3777 if (!*p)
3778 break;
3779 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3780 p += 1 + strspn(p + 1, " \t\n");
3781 oneline_offset = p - arg;
3782 break;
3784 k = strcspn(p, " \t\n");
3785 if (!k)
3786 continue;
3787 merge_commit = lookup_label(p, k, &ref_name);
3788 if (!merge_commit) {
3789 ret = error(_("unable to parse '%.*s'"), k, p);
3790 goto leave_merge;
3792 tail = &commit_list_insert(merge_commit, tail)->next;
3793 p += k;
3794 merge_arg_len = p - arg;
3797 if (!to_merge) {
3798 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3799 goto leave_merge;
3802 if (opts->have_squash_onto &&
3803 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3805 * When the user tells us to "merge" something into a
3806 * "[new root]", let's simply fast-forward to the merge head.
3808 rollback_lock_file(&lock);
3809 if (to_merge->next)
3810 ret = error(_("octopus merge cannot be executed on "
3811 "top of a [new root]"));
3812 else
3813 ret = fast_forward_to(r, &to_merge->item->object.oid,
3814 &head_commit->object.oid, 0,
3815 opts);
3816 goto leave_merge;
3820 * If HEAD is not identical to the first parent of the original merge
3821 * commit, we cannot fast-forward.
3823 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3824 oideq(&commit->parents->item->object.oid,
3825 &head_commit->object.oid);
3828 * If any merge head is different from the original one, we cannot
3829 * fast-forward.
3831 if (can_fast_forward) {
3832 struct commit_list *p = commit->parents->next;
3834 for (j = to_merge; j && p; j = j->next, p = p->next)
3835 if (!oideq(&j->item->object.oid,
3836 &p->item->object.oid)) {
3837 can_fast_forward = 0;
3838 break;
3841 * If the number of merge heads differs from the original merge
3842 * commit, we cannot fast-forward.
3844 if (j || p)
3845 can_fast_forward = 0;
3848 if (can_fast_forward) {
3849 rollback_lock_file(&lock);
3850 ret = fast_forward_to(r, &commit->object.oid,
3851 &head_commit->object.oid, 0, opts);
3852 if (flags & TODO_EDIT_MERGE_MSG)
3853 goto fast_forward_edit;
3855 goto leave_merge;
3858 if (commit) {
3859 const char *encoding = get_commit_output_encoding();
3860 const char *message = logmsg_reencode(commit, NULL, encoding);
3861 const char *body;
3862 int len;
3864 if (!message) {
3865 ret = error(_("could not get commit message of '%s'"),
3866 oid_to_hex(&commit->object.oid));
3867 goto leave_merge;
3869 write_author_script(message);
3870 find_commit_subject(message, &body);
3871 len = strlen(body);
3872 ret = write_message(body, len, git_path_merge_msg(r), 0);
3873 unuse_commit_buffer(commit, message);
3874 if (ret) {
3875 error_errno(_("could not write '%s'"),
3876 git_path_merge_msg(r));
3877 goto leave_merge;
3879 } else {
3880 struct strbuf buf = STRBUF_INIT;
3881 int len;
3883 strbuf_addf(&buf, "author %s", git_author_info(0));
3884 write_author_script(buf.buf);
3885 strbuf_reset(&buf);
3887 if (oneline_offset < arg_len) {
3888 p = arg + oneline_offset;
3889 len = arg_len - oneline_offset;
3890 } else {
3891 strbuf_addf(&buf, "Merge %s '%.*s'",
3892 to_merge->next ? "branches" : "branch",
3893 merge_arg_len, arg);
3894 p = buf.buf;
3895 len = buf.len;
3898 ret = write_message(p, len, git_path_merge_msg(r), 0);
3899 strbuf_release(&buf);
3900 if (ret) {
3901 error_errno(_("could not write '%s'"),
3902 git_path_merge_msg(r));
3903 goto leave_merge;
3907 if (strategy || to_merge->next) {
3908 /* Octopus merge */
3909 struct child_process cmd = CHILD_PROCESS_INIT;
3911 if (read_env_script(&cmd.env_array)) {
3912 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3914 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3915 goto leave_merge;
3918 if (opts->committer_date_is_author_date)
3919 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3920 opts->ignore_date ?
3921 "" :
3922 author_date_from_env_array(&cmd.env_array));
3923 if (opts->ignore_date)
3924 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3926 cmd.git_cmd = 1;
3927 strvec_push(&cmd.args, "merge");
3928 strvec_push(&cmd.args, "-s");
3929 if (!strategy)
3930 strvec_push(&cmd.args, "octopus");
3931 else {
3932 strvec_push(&cmd.args, strategy);
3933 for (k = 0; k < opts->xopts_nr; k++)
3934 strvec_pushf(&cmd.args,
3935 "-X%s", opts->xopts[k]);
3937 if (!(flags & TODO_EDIT_MERGE_MSG))
3938 strvec_push(&cmd.args, "--no-edit");
3939 else
3940 strvec_push(&cmd.args, "--edit");
3941 strvec_push(&cmd.args, "--no-ff");
3942 strvec_push(&cmd.args, "--no-log");
3943 strvec_push(&cmd.args, "--no-stat");
3944 strvec_push(&cmd.args, "-F");
3945 strvec_push(&cmd.args, git_path_merge_msg(r));
3946 if (opts->gpg_sign)
3947 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3948 else
3949 strvec_push(&cmd.args, "--no-gpg-sign");
3951 /* Add the tips to be merged */
3952 for (j = to_merge; j; j = j->next)
3953 strvec_push(&cmd.args,
3954 oid_to_hex(&j->item->object.oid));
3956 strbuf_release(&ref_name);
3957 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3958 NULL, 0);
3959 rollback_lock_file(&lock);
3961 ret = run_command(&cmd);
3963 /* force re-reading of the cache */
3964 if (!ret && (discard_index(r->index) < 0 ||
3965 repo_read_index(r) < 0))
3966 ret = error(_("could not read index"));
3967 goto leave_merge;
3970 merge_commit = to_merge->item;
3971 bases = get_merge_bases(head_commit, merge_commit);
3972 if (bases && oideq(&merge_commit->object.oid,
3973 &bases->item->object.oid)) {
3974 ret = 0;
3975 /* skip merging an ancestor of HEAD */
3976 goto leave_merge;
3979 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3980 git_path_merge_head(r), 0);
3981 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3983 for (j = bases; j; j = j->next)
3984 commit_list_insert(j->item, &reversed);
3985 free_commit_list(bases);
3987 repo_read_index(r);
3988 init_merge_options(&o, r);
3989 o.branch1 = "HEAD";
3990 o.branch2 = ref_name.buf;
3991 o.buffer_output = 2;
3993 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3995 * TODO: Should use merge_incore_recursive() and
3996 * merge_switch_to_result(), skipping the call to
3997 * merge_switch_to_result() when we don't actually need to
3998 * update the index and working copy immediately.
4000 ret = merge_ort_recursive(&o,
4001 head_commit, merge_commit, reversed,
4002 &i);
4003 } else {
4004 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4005 &i);
4007 if (ret <= 0)
4008 fputs(o.obuf.buf, stdout);
4009 strbuf_release(&o.obuf);
4010 if (ret < 0) {
4011 error(_("could not even attempt to merge '%.*s'"),
4012 merge_arg_len, arg);
4013 goto leave_merge;
4016 * The return value of merge_recursive() is 1 on clean, and 0 on
4017 * unclean merge.
4019 * Let's reverse that, so that do_merge() returns 0 upon success and
4020 * 1 upon failed merge (keeping the return value -1 for the cases where
4021 * we will want to reschedule the `merge` command).
4023 ret = !ret;
4025 if (r->index->cache_changed &&
4026 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4027 ret = error(_("merge: Unable to write new index file"));
4028 goto leave_merge;
4031 rollback_lock_file(&lock);
4032 if (ret)
4033 repo_rerere(r, opts->allow_rerere_auto);
4034 else
4036 * In case of problems, we now want to return a positive
4037 * value (a negative one would indicate that the `merge`
4038 * command needs to be rescheduled).
4040 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4041 run_commit_flags);
4043 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4044 fast_forward_edit:
4045 *check_todo = 1;
4046 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4047 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4051 leave_merge:
4052 strbuf_release(&ref_name);
4053 rollback_lock_file(&lock);
4054 free_commit_list(to_merge);
4055 return ret;
4058 static int is_final_fixup(struct todo_list *todo_list)
4060 int i = todo_list->current;
4062 if (!is_fixup(todo_list->items[i].command))
4063 return 0;
4065 while (++i < todo_list->nr)
4066 if (is_fixup(todo_list->items[i].command))
4067 return 0;
4068 else if (!is_noop(todo_list->items[i].command))
4069 break;
4070 return 1;
4073 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4075 int i;
4077 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4078 if (!is_noop(todo_list->items[i].command))
4079 return todo_list->items[i].command;
4081 return -1;
4084 void create_autostash(struct repository *r, const char *path,
4085 const char *default_reflog_action)
4087 struct strbuf buf = STRBUF_INIT;
4088 struct lock_file lock_file = LOCK_INIT;
4089 int fd;
4091 fd = repo_hold_locked_index(r, &lock_file, 0);
4092 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4093 if (0 <= fd)
4094 repo_update_index_if_able(r, &lock_file);
4095 rollback_lock_file(&lock_file);
4097 if (has_unstaged_changes(r, 1) ||
4098 has_uncommitted_changes(r, 1)) {
4099 struct child_process stash = CHILD_PROCESS_INIT;
4100 struct object_id oid;
4102 strvec_pushl(&stash.args,
4103 "stash", "create", "autostash", NULL);
4104 stash.git_cmd = 1;
4105 stash.no_stdin = 1;
4106 strbuf_reset(&buf);
4107 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4108 die(_("Cannot autostash"));
4109 strbuf_trim_trailing_newline(&buf);
4110 if (get_oid(buf.buf, &oid))
4111 die(_("Unexpected stash response: '%s'"),
4112 buf.buf);
4113 strbuf_reset(&buf);
4114 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4116 if (safe_create_leading_directories_const(path))
4117 die(_("Could not create directory for '%s'"),
4118 path);
4119 write_file(path, "%s", oid_to_hex(&oid));
4120 printf(_("Created autostash: %s\n"), buf.buf);
4121 if (reset_head(r, NULL, "reset --hard",
4122 NULL, RESET_HEAD_HARD, NULL, NULL,
4123 default_reflog_action) < 0)
4124 die(_("could not reset --hard"));
4126 if (discard_index(r->index) < 0 ||
4127 repo_read_index(r) < 0)
4128 die(_("could not read index"));
4130 strbuf_release(&buf);
4133 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4135 struct child_process child = CHILD_PROCESS_INIT;
4136 int ret = 0;
4138 if (attempt_apply) {
4139 child.git_cmd = 1;
4140 child.no_stdout = 1;
4141 child.no_stderr = 1;
4142 strvec_push(&child.args, "stash");
4143 strvec_push(&child.args, "apply");
4144 strvec_push(&child.args, stash_oid);
4145 ret = run_command(&child);
4148 if (attempt_apply && !ret)
4149 fprintf(stderr, _("Applied autostash.\n"));
4150 else {
4151 struct child_process store = CHILD_PROCESS_INIT;
4153 store.git_cmd = 1;
4154 strvec_push(&store.args, "stash");
4155 strvec_push(&store.args, "store");
4156 strvec_push(&store.args, "-m");
4157 strvec_push(&store.args, "autostash");
4158 strvec_push(&store.args, "-q");
4159 strvec_push(&store.args, stash_oid);
4160 if (run_command(&store))
4161 ret = error(_("cannot store %s"), stash_oid);
4162 else
4163 fprintf(stderr,
4164 _("%s\n"
4165 "Your changes are safe in the stash.\n"
4166 "You can run \"git stash pop\" or"
4167 " \"git stash drop\" at any time.\n"),
4168 attempt_apply ?
4169 _("Applying autostash resulted in conflicts.") :
4170 _("Autostash exists; creating a new stash entry."));
4173 return ret;
4176 static int apply_save_autostash(const char *path, int attempt_apply)
4178 struct strbuf stash_oid = STRBUF_INIT;
4179 int ret = 0;
4181 if (!read_oneliner(&stash_oid, path,
4182 READ_ONELINER_SKIP_IF_EMPTY)) {
4183 strbuf_release(&stash_oid);
4184 return 0;
4186 strbuf_trim(&stash_oid);
4188 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4190 unlink(path);
4191 strbuf_release(&stash_oid);
4192 return ret;
4195 int save_autostash(const char *path)
4197 return apply_save_autostash(path, 0);
4200 int apply_autostash(const char *path)
4202 return apply_save_autostash(path, 1);
4205 int apply_autostash_oid(const char *stash_oid)
4207 return apply_save_autostash_oid(stash_oid, 1);
4210 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4211 const char *commit, const char *action)
4213 struct child_process cmd = CHILD_PROCESS_INIT;
4214 int ret;
4216 cmd.git_cmd = 1;
4218 strvec_push(&cmd.args, "checkout");
4219 strvec_push(&cmd.args, commit);
4220 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4222 if (opts->verbose)
4223 ret = run_command(&cmd);
4224 else
4225 ret = run_command_silent_on_success(&cmd);
4227 if (!ret)
4228 discard_index(r->index);
4230 return ret;
4233 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4234 const char *onto_name, const struct object_id *onto,
4235 const struct object_id *orig_head)
4237 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4239 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4240 apply_autostash(rebase_path_autostash());
4241 sequencer_remove_state(opts);
4242 return error(_("could not detach HEAD"));
4245 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4248 static int stopped_at_head(struct repository *r)
4250 struct object_id head;
4251 struct commit *commit;
4252 struct commit_message message;
4254 if (get_oid("HEAD", &head) ||
4255 !(commit = lookup_commit(r, &head)) ||
4256 parse_commit(commit) || get_message(commit, &message))
4257 fprintf(stderr, _("Stopped at HEAD\n"));
4258 else {
4259 fprintf(stderr, _("Stopped at %s\n"), message.label);
4260 free_message(commit, &message);
4262 return 0;
4266 static const char rescheduled_advice[] =
4267 N_("Could not execute the todo command\n"
4268 "\n"
4269 " %.*s"
4270 "\n"
4271 "It has been rescheduled; To edit the command before continuing, please\n"
4272 "edit the todo list first:\n"
4273 "\n"
4274 " git rebase --edit-todo\n"
4275 " git rebase --continue\n");
4277 static int pick_commits(struct repository *r,
4278 struct todo_list *todo_list,
4279 struct replay_opts *opts)
4281 int res = 0, reschedule = 0;
4282 char *prev_reflog_action;
4284 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4285 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4286 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4287 if (opts->allow_ff)
4288 assert(!(opts->signoff || opts->no_commit ||
4289 opts->record_origin || should_edit(opts) ||
4290 opts->committer_date_is_author_date ||
4291 opts->ignore_date));
4292 if (read_and_refresh_cache(r, opts))
4293 return -1;
4295 while (todo_list->current < todo_list->nr) {
4296 struct todo_item *item = todo_list->items + todo_list->current;
4297 const char *arg = todo_item_get_arg(todo_list, item);
4298 int check_todo = 0;
4300 if (save_todo(todo_list, opts))
4301 return -1;
4302 if (is_rebase_i(opts)) {
4303 if (item->command != TODO_COMMENT) {
4304 FILE *f = fopen(rebase_path_msgnum(), "w");
4306 todo_list->done_nr++;
4308 if (f) {
4309 fprintf(f, "%d\n", todo_list->done_nr);
4310 fclose(f);
4312 if (!opts->quiet)
4313 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4314 todo_list->done_nr,
4315 todo_list->total_nr,
4316 opts->verbose ? "\n" : "\r");
4318 unlink(rebase_path_message());
4319 unlink(rebase_path_author_script());
4320 unlink(rebase_path_stopped_sha());
4321 unlink(rebase_path_amend());
4322 unlink(git_path_merge_head(r));
4323 unlink(git_path_auto_merge(r));
4324 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4326 if (item->command == TODO_BREAK) {
4327 if (!opts->verbose)
4328 term_clear_line();
4329 return stopped_at_head(r);
4332 if (item->command <= TODO_SQUASH) {
4333 if (is_rebase_i(opts))
4334 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4335 command_to_string(item->command), NULL),
4337 res = do_pick_commit(r, item, opts,
4338 is_final_fixup(todo_list),
4339 &check_todo);
4340 if (is_rebase_i(opts))
4341 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4342 if (is_rebase_i(opts) && res < 0) {
4343 /* Reschedule */
4344 advise(_(rescheduled_advice),
4345 get_item_line_length(todo_list,
4346 todo_list->current),
4347 get_item_line(todo_list,
4348 todo_list->current));
4349 todo_list->current--;
4350 if (save_todo(todo_list, opts))
4351 return -1;
4353 if (item->command == TODO_EDIT) {
4354 struct commit *commit = item->commit;
4355 if (!res) {
4356 if (!opts->verbose)
4357 term_clear_line();
4358 fprintf(stderr,
4359 _("Stopped at %s... %.*s\n"),
4360 short_commit_name(commit),
4361 item->arg_len, arg);
4363 return error_with_patch(r, commit,
4364 arg, item->arg_len, opts, res, !res);
4366 if (is_rebase_i(opts) && !res)
4367 record_in_rewritten(&item->commit->object.oid,
4368 peek_command(todo_list, 1));
4369 if (res && is_fixup(item->command)) {
4370 if (res == 1)
4371 intend_to_amend();
4372 return error_failed_squash(r, item->commit, opts,
4373 item->arg_len, arg);
4374 } else if (res && is_rebase_i(opts) && item->commit) {
4375 int to_amend = 0;
4376 struct object_id oid;
4379 * If we are rewording and have either
4380 * fast-forwarded already, or are about to
4381 * create a new root commit, we want to amend,
4382 * otherwise we do not.
4384 if (item->command == TODO_REWORD &&
4385 !get_oid("HEAD", &oid) &&
4386 (oideq(&item->commit->object.oid, &oid) ||
4387 (opts->have_squash_onto &&
4388 oideq(&opts->squash_onto, &oid))))
4389 to_amend = 1;
4391 return res | error_with_patch(r, item->commit,
4392 arg, item->arg_len, opts,
4393 res, to_amend);
4395 } else if (item->command == TODO_EXEC) {
4396 char *end_of_arg = (char *)(arg + item->arg_len);
4397 int saved = *end_of_arg;
4399 if (!opts->verbose)
4400 term_clear_line();
4401 *end_of_arg = '\0';
4402 res = do_exec(r, arg);
4403 *end_of_arg = saved;
4405 if (res) {
4406 if (opts->reschedule_failed_exec)
4407 reschedule = 1;
4409 check_todo = 1;
4410 } else if (item->command == TODO_LABEL) {
4411 if ((res = do_label(r, arg, item->arg_len)))
4412 reschedule = 1;
4413 } else if (item->command == TODO_RESET) {
4414 if ((res = do_reset(r, arg, item->arg_len, opts)))
4415 reschedule = 1;
4416 } else if (item->command == TODO_MERGE) {
4417 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4418 item->flags, &check_todo, opts)) < 0)
4419 reschedule = 1;
4420 else if (item->commit)
4421 record_in_rewritten(&item->commit->object.oid,
4422 peek_command(todo_list, 1));
4423 if (res > 0)
4424 /* failed with merge conflicts */
4425 return error_with_patch(r, item->commit,
4426 arg, item->arg_len,
4427 opts, res, 0);
4428 } else if (!is_noop(item->command))
4429 return error(_("unknown command %d"), item->command);
4431 if (reschedule) {
4432 advise(_(rescheduled_advice),
4433 get_item_line_length(todo_list,
4434 todo_list->current),
4435 get_item_line(todo_list, todo_list->current));
4436 todo_list->current--;
4437 if (save_todo(todo_list, opts))
4438 return -1;
4439 if (item->commit)
4440 return error_with_patch(r,
4441 item->commit,
4442 arg, item->arg_len,
4443 opts, res, 0);
4444 } else if (is_rebase_i(opts) && check_todo && !res) {
4445 struct stat st;
4447 if (stat(get_todo_path(opts), &st)) {
4448 res = error_errno(_("could not stat '%s'"),
4449 get_todo_path(opts));
4450 } else if (match_stat_data(&todo_list->stat, &st)) {
4451 /* Reread the todo file if it has changed. */
4452 todo_list_release(todo_list);
4453 if (read_populate_todo(r, todo_list, opts))
4454 res = -1; /* message was printed */
4455 /* `current` will be incremented below */
4456 todo_list->current = -1;
4460 todo_list->current++;
4461 if (res)
4462 return res;
4465 if (is_rebase_i(opts)) {
4466 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4467 struct stat st;
4469 /* Stopped in the middle, as planned? */
4470 if (todo_list->current < todo_list->nr)
4471 return 0;
4473 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4474 starts_with(head_ref.buf, "refs/")) {
4475 const char *msg;
4476 struct object_id head, orig;
4477 int res;
4479 if (get_oid("HEAD", &head)) {
4480 res = error(_("cannot read HEAD"));
4481 cleanup_head_ref:
4482 strbuf_release(&head_ref);
4483 strbuf_release(&buf);
4484 return res;
4486 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4487 get_oid_hex(buf.buf, &orig)) {
4488 res = error(_("could not read orig-head"));
4489 goto cleanup_head_ref;
4491 strbuf_reset(&buf);
4492 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4493 res = error(_("could not read 'onto'"));
4494 goto cleanup_head_ref;
4496 msg = reflog_message(opts, "finish", "%s onto %s",
4497 head_ref.buf, buf.buf);
4498 if (update_ref(msg, head_ref.buf, &head, &orig,
4499 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4500 res = error(_("could not update %s"),
4501 head_ref.buf);
4502 goto cleanup_head_ref;
4504 msg = reflog_message(opts, "finish", "returning to %s",
4505 head_ref.buf);
4506 if (create_symref("HEAD", head_ref.buf, msg)) {
4507 res = error(_("could not update HEAD to %s"),
4508 head_ref.buf);
4509 goto cleanup_head_ref;
4511 strbuf_reset(&buf);
4514 if (opts->verbose) {
4515 struct rev_info log_tree_opt;
4516 struct object_id orig, head;
4518 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4519 repo_init_revisions(r, &log_tree_opt, NULL);
4520 log_tree_opt.diff = 1;
4521 log_tree_opt.diffopt.output_format =
4522 DIFF_FORMAT_DIFFSTAT;
4523 log_tree_opt.disable_stdin = 1;
4525 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4526 !get_oid(buf.buf, &orig) &&
4527 !get_oid("HEAD", &head)) {
4528 diff_tree_oid(&orig, &head, "",
4529 &log_tree_opt.diffopt);
4530 log_tree_diff_flush(&log_tree_opt);
4533 flush_rewritten_pending();
4534 if (!stat(rebase_path_rewritten_list(), &st) &&
4535 st.st_size > 0) {
4536 struct child_process child = CHILD_PROCESS_INIT;
4537 const char *post_rewrite_hook =
4538 find_hook("post-rewrite");
4540 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4541 child.git_cmd = 1;
4542 strvec_push(&child.args, "notes");
4543 strvec_push(&child.args, "copy");
4544 strvec_push(&child.args, "--for-rewrite=rebase");
4545 /* we don't care if this copying failed */
4546 run_command(&child);
4548 if (post_rewrite_hook) {
4549 struct child_process hook = CHILD_PROCESS_INIT;
4551 hook.in = open(rebase_path_rewritten_list(),
4552 O_RDONLY);
4553 hook.stdout_to_stderr = 1;
4554 hook.trace2_hook_name = "post-rewrite";
4555 strvec_push(&hook.args, post_rewrite_hook);
4556 strvec_push(&hook.args, "rebase");
4557 /* we don't care if this hook failed */
4558 run_command(&hook);
4561 apply_autostash(rebase_path_autostash());
4563 if (!opts->quiet) {
4564 if (!opts->verbose)
4565 term_clear_line();
4566 fprintf(stderr,
4567 _("Successfully rebased and updated %s.\n"),
4568 head_ref.buf);
4571 strbuf_release(&buf);
4572 strbuf_release(&head_ref);
4576 * Sequence of picks finished successfully; cleanup by
4577 * removing the .git/sequencer directory
4579 return sequencer_remove_state(opts);
4582 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4584 struct strvec argv = STRVEC_INIT;
4585 int ret;
4587 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4588 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4589 return error(_("no cherry-pick or revert in progress"));
4591 strvec_push(&argv, "commit");
4594 * continue_single_pick() handles the case of recovering from a
4595 * conflict. should_edit() doesn't handle that case; for a conflict,
4596 * we want to edit if the user asked for it, or if they didn't specify
4597 * and stdin is a tty.
4599 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4601 * Include --cleanup=strip as well because we don't want the
4602 * "# Conflicts:" messages.
4604 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4606 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4607 strvec_clear(&argv);
4608 return ret;
4611 static int commit_staged_changes(struct repository *r,
4612 struct replay_opts *opts,
4613 struct todo_list *todo_list)
4615 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4616 unsigned int final_fixup = 0, is_clean;
4618 if (has_unstaged_changes(r, 1))
4619 return error(_("cannot rebase: You have unstaged changes."));
4621 is_clean = !has_uncommitted_changes(r, 0);
4623 if (file_exists(rebase_path_amend())) {
4624 struct strbuf rev = STRBUF_INIT;
4625 struct object_id head, to_amend;
4627 if (get_oid("HEAD", &head))
4628 return error(_("cannot amend non-existing commit"));
4629 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4630 return error(_("invalid file: '%s'"), rebase_path_amend());
4631 if (get_oid_hex(rev.buf, &to_amend))
4632 return error(_("invalid contents: '%s'"),
4633 rebase_path_amend());
4634 if (!is_clean && !oideq(&head, &to_amend))
4635 return error(_("\nYou have uncommitted changes in your "
4636 "working tree. Please, commit them\n"
4637 "first and then run 'git rebase "
4638 "--continue' again."));
4640 * When skipping a failed fixup/squash, we need to edit the
4641 * commit message, the current fixup list and count, and if it
4642 * was the last fixup/squash in the chain, we need to clean up
4643 * the commit message and if there was a squash, let the user
4644 * edit it.
4646 if (!is_clean || !opts->current_fixup_count)
4647 ; /* this is not the final fixup */
4648 else if (!oideq(&head, &to_amend) ||
4649 !file_exists(rebase_path_stopped_sha())) {
4650 /* was a final fixup or squash done manually? */
4651 if (!is_fixup(peek_command(todo_list, 0))) {
4652 unlink(rebase_path_fixup_msg());
4653 unlink(rebase_path_squash_msg());
4654 unlink(rebase_path_current_fixups());
4655 strbuf_reset(&opts->current_fixups);
4656 opts->current_fixup_count = 0;
4658 } else {
4659 /* we are in a fixup/squash chain */
4660 const char *p = opts->current_fixups.buf;
4661 int len = opts->current_fixups.len;
4663 opts->current_fixup_count--;
4664 if (!len)
4665 BUG("Incorrect current_fixups:\n%s", p);
4666 while (len && p[len - 1] != '\n')
4667 len--;
4668 strbuf_setlen(&opts->current_fixups, len);
4669 if (write_message(p, len, rebase_path_current_fixups(),
4670 0) < 0)
4671 return error(_("could not write file: '%s'"),
4672 rebase_path_current_fixups());
4675 * If a fixup/squash in a fixup/squash chain failed, the
4676 * commit message is already correct, no need to commit
4677 * it again.
4679 * Only if it is the final command in the fixup/squash
4680 * chain, and only if the chain is longer than a single
4681 * fixup/squash command (which was just skipped), do we
4682 * actually need to re-commit with a cleaned up commit
4683 * message.
4685 if (opts->current_fixup_count > 0 &&
4686 !is_fixup(peek_command(todo_list, 0))) {
4687 final_fixup = 1;
4689 * If there was not a single "squash" in the
4690 * chain, we only need to clean up the commit
4691 * message, no need to bother the user with
4692 * opening the commit message in the editor.
4694 if (!starts_with(p, "squash ") &&
4695 !strstr(p, "\nsquash "))
4696 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4697 } else if (is_fixup(peek_command(todo_list, 0))) {
4699 * We need to update the squash message to skip
4700 * the latest commit message.
4702 struct commit *commit;
4703 const char *path = rebase_path_squash_msg();
4704 const char *encoding = get_commit_output_encoding();
4706 if (parse_head(r, &commit) ||
4707 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4708 write_message(p, strlen(p), path, 0)) {
4709 unuse_commit_buffer(commit, p);
4710 return error(_("could not write file: "
4711 "'%s'"), path);
4713 unuse_commit_buffer(commit, p);
4717 strbuf_release(&rev);
4718 flags |= AMEND_MSG;
4721 if (is_clean) {
4722 if (refs_ref_exists(get_main_ref_store(r),
4723 "CHERRY_PICK_HEAD") &&
4724 refs_delete_ref(get_main_ref_store(r), "",
4725 "CHERRY_PICK_HEAD", NULL, 0))
4726 return error(_("could not remove CHERRY_PICK_HEAD"));
4727 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
4728 return error_errno(_("could not remove '%s'"),
4729 git_path_merge_msg(r));
4730 if (!final_fixup)
4731 return 0;
4734 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4735 opts, flags))
4736 return error(_("could not commit staged changes."));
4737 unlink(rebase_path_amend());
4738 unlink(git_path_merge_head(r));
4739 unlink(git_path_auto_merge(r));
4740 if (final_fixup) {
4741 unlink(rebase_path_fixup_msg());
4742 unlink(rebase_path_squash_msg());
4744 if (opts->current_fixup_count > 0) {
4746 * Whether final fixup or not, we just cleaned up the commit
4747 * message...
4749 unlink(rebase_path_current_fixups());
4750 strbuf_reset(&opts->current_fixups);
4751 opts->current_fixup_count = 0;
4753 return 0;
4756 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4758 struct todo_list todo_list = TODO_LIST_INIT;
4759 int res;
4761 if (read_and_refresh_cache(r, opts))
4762 return -1;
4764 if (read_populate_opts(opts))
4765 return -1;
4766 if (is_rebase_i(opts)) {
4767 if ((res = read_populate_todo(r, &todo_list, opts)))
4768 goto release_todo_list;
4770 if (file_exists(rebase_path_dropped())) {
4771 if ((res = todo_list_check_against_backup(r, &todo_list)))
4772 goto release_todo_list;
4774 unlink(rebase_path_dropped());
4777 if (commit_staged_changes(r, opts, &todo_list)) {
4778 res = -1;
4779 goto release_todo_list;
4781 } else if (!file_exists(get_todo_path(opts)))
4782 return continue_single_pick(r, opts);
4783 else if ((res = read_populate_todo(r, &todo_list, opts)))
4784 goto release_todo_list;
4786 if (!is_rebase_i(opts)) {
4787 /* Verify that the conflict has been resolved */
4788 if (refs_ref_exists(get_main_ref_store(r),
4789 "CHERRY_PICK_HEAD") ||
4790 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4791 res = continue_single_pick(r, opts);
4792 if (res)
4793 goto release_todo_list;
4795 if (index_differs_from(r, "HEAD", NULL, 0)) {
4796 res = error_dirty_index(r, opts);
4797 goto release_todo_list;
4799 todo_list.current++;
4800 } else if (file_exists(rebase_path_stopped_sha())) {
4801 struct strbuf buf = STRBUF_INIT;
4802 struct object_id oid;
4804 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4805 READ_ONELINER_SKIP_IF_EMPTY) &&
4806 !get_oid_hex(buf.buf, &oid))
4807 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4808 strbuf_release(&buf);
4811 res = pick_commits(r, &todo_list, opts);
4812 release_todo_list:
4813 todo_list_release(&todo_list);
4814 return res;
4817 static int single_pick(struct repository *r,
4818 struct commit *cmit,
4819 struct replay_opts *opts)
4821 int check_todo;
4822 struct todo_item item;
4824 item.command = opts->action == REPLAY_PICK ?
4825 TODO_PICK : TODO_REVERT;
4826 item.commit = cmit;
4828 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4829 return do_pick_commit(r, &item, opts, 0, &check_todo);
4832 int sequencer_pick_revisions(struct repository *r,
4833 struct replay_opts *opts)
4835 struct todo_list todo_list = TODO_LIST_INIT;
4836 struct object_id oid;
4837 int i, res;
4839 assert(opts->revs);
4840 if (read_and_refresh_cache(r, opts))
4841 return -1;
4843 for (i = 0; i < opts->revs->pending.nr; i++) {
4844 struct object_id oid;
4845 const char *name = opts->revs->pending.objects[i].name;
4847 /* This happens when using --stdin. */
4848 if (!strlen(name))
4849 continue;
4851 if (!get_oid(name, &oid)) {
4852 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4853 enum object_type type = oid_object_info(r,
4854 &oid,
4855 NULL);
4856 return error(_("%s: can't cherry-pick a %s"),
4857 name, type_name(type));
4859 } else
4860 return error(_("%s: bad revision"), name);
4864 * If we were called as "git cherry-pick <commit>", just
4865 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4866 * REVERT_HEAD, and don't touch the sequencer state.
4867 * This means it is possible to cherry-pick in the middle
4868 * of a cherry-pick sequence.
4870 if (opts->revs->cmdline.nr == 1 &&
4871 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4872 opts->revs->no_walk &&
4873 !opts->revs->cmdline.rev->flags) {
4874 struct commit *cmit;
4875 if (prepare_revision_walk(opts->revs))
4876 return error(_("revision walk setup failed"));
4877 cmit = get_revision(opts->revs);
4878 if (!cmit)
4879 return error(_("empty commit set passed"));
4880 if (get_revision(opts->revs))
4881 BUG("unexpected extra commit from walk");
4882 return single_pick(r, cmit, opts);
4886 * Start a new cherry-pick/ revert sequence; but
4887 * first, make sure that an existing one isn't in
4888 * progress
4891 if (walk_revs_populate_todo(&todo_list, opts) ||
4892 create_seq_dir(r) < 0)
4893 return -1;
4894 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4895 return error(_("can't revert as initial commit"));
4896 if (save_head(oid_to_hex(&oid)))
4897 return -1;
4898 if (save_opts(opts))
4899 return -1;
4900 update_abort_safety_file();
4901 res = pick_commits(r, &todo_list, opts);
4902 todo_list_release(&todo_list);
4903 return res;
4906 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4908 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4909 struct strbuf sob = STRBUF_INIT;
4910 int has_footer;
4912 strbuf_addstr(&sob, sign_off_header);
4913 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4914 strbuf_addch(&sob, '\n');
4916 if (!ignore_footer)
4917 strbuf_complete_line(msgbuf);
4920 * If the whole message buffer is equal to the sob, pretend that we
4921 * found a conforming footer with a matching sob
4923 if (msgbuf->len - ignore_footer == sob.len &&
4924 !strncmp(msgbuf->buf, sob.buf, sob.len))
4925 has_footer = 3;
4926 else
4927 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4929 if (!has_footer) {
4930 const char *append_newlines = NULL;
4931 size_t len = msgbuf->len - ignore_footer;
4933 if (!len) {
4935 * The buffer is completely empty. Leave foom for
4936 * the title and body to be filled in by the user.
4938 append_newlines = "\n\n";
4939 } else if (len == 1) {
4941 * Buffer contains a single newline. Add another
4942 * so that we leave room for the title and body.
4944 append_newlines = "\n";
4945 } else if (msgbuf->buf[len - 2] != '\n') {
4947 * Buffer ends with a single newline. Add another
4948 * so that there is an empty line between the message
4949 * body and the sob.
4951 append_newlines = "\n";
4952 } /* else, the buffer already ends with two newlines. */
4954 if (append_newlines)
4955 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4956 append_newlines, strlen(append_newlines));
4959 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4960 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4961 sob.buf, sob.len);
4963 strbuf_release(&sob);
4966 struct labels_entry {
4967 struct hashmap_entry entry;
4968 char label[FLEX_ARRAY];
4971 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4972 const struct hashmap_entry *entry_or_key, const void *key)
4974 const struct labels_entry *a, *b;
4976 a = container_of(eptr, const struct labels_entry, entry);
4977 b = container_of(entry_or_key, const struct labels_entry, entry);
4979 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4982 struct string_entry {
4983 struct oidmap_entry entry;
4984 char string[FLEX_ARRAY];
4987 struct label_state {
4988 struct oidmap commit2label;
4989 struct hashmap labels;
4990 struct strbuf buf;
4993 static const char *label_oid(struct object_id *oid, const char *label,
4994 struct label_state *state)
4996 struct labels_entry *labels_entry;
4997 struct string_entry *string_entry;
4998 struct object_id dummy;
4999 int i;
5001 string_entry = oidmap_get(&state->commit2label, oid);
5002 if (string_entry)
5003 return string_entry->string;
5006 * For "uninteresting" commits, i.e. commits that are not to be
5007 * rebased, and which can therefore not be labeled, we use a unique
5008 * abbreviation of the commit name. This is slightly more complicated
5009 * than calling find_unique_abbrev() because we also need to make
5010 * sure that the abbreviation does not conflict with any other
5011 * label.
5013 * We disallow "interesting" commits to be labeled by a string that
5014 * is a valid full-length hash, to ensure that we always can find an
5015 * abbreviation for any uninteresting commit's names that does not
5016 * clash with any other label.
5018 strbuf_reset(&state->buf);
5019 if (!label) {
5020 char *p;
5022 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5023 label = p = state->buf.buf;
5025 find_unique_abbrev_r(p, oid, default_abbrev);
5028 * We may need to extend the abbreviated hash so that there is
5029 * no conflicting label.
5031 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5032 size_t i = strlen(p) + 1;
5034 oid_to_hex_r(p, oid);
5035 for (; i < the_hash_algo->hexsz; i++) {
5036 char save = p[i];
5037 p[i] = '\0';
5038 if (!hashmap_get_from_hash(&state->labels,
5039 strihash(p), p))
5040 break;
5041 p[i] = save;
5044 } else {
5045 struct strbuf *buf = &state->buf;
5048 * Sanitize labels by replacing non-alpha-numeric characters
5049 * (including white-space ones) by dashes, as they might be
5050 * illegal in file names (and hence in ref names).
5052 * Note that we retain non-ASCII UTF-8 characters (identified
5053 * via the most significant bit). They should be all acceptable
5054 * in file names. We do not validate the UTF-8 here, that's not
5055 * the job of this function.
5057 for (; *label; label++)
5058 if ((*label & 0x80) || isalnum(*label))
5059 strbuf_addch(buf, *label);
5060 /* avoid leading dash and double-dashes */
5061 else if (buf->len && buf->buf[buf->len - 1] != '-')
5062 strbuf_addch(buf, '-');
5063 if (!buf->len) {
5064 strbuf_addstr(buf, "rev-");
5065 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5067 label = buf->buf;
5069 if ((buf->len == the_hash_algo->hexsz &&
5070 !get_oid_hex(label, &dummy)) ||
5071 (buf->len == 1 && *label == '#') ||
5072 hashmap_get_from_hash(&state->labels,
5073 strihash(label), label)) {
5075 * If the label already exists, or if the label is a
5076 * valid full OID, or the label is a '#' (which we use
5077 * as a separator between merge heads and oneline), we
5078 * append a dash and a number to make it unique.
5080 size_t len = buf->len;
5082 for (i = 2; ; i++) {
5083 strbuf_setlen(buf, len);
5084 strbuf_addf(buf, "-%d", i);
5085 if (!hashmap_get_from_hash(&state->labels,
5086 strihash(buf->buf),
5087 buf->buf))
5088 break;
5091 label = buf->buf;
5095 FLEX_ALLOC_STR(labels_entry, label, label);
5096 hashmap_entry_init(&labels_entry->entry, strihash(label));
5097 hashmap_add(&state->labels, &labels_entry->entry);
5099 FLEX_ALLOC_STR(string_entry, string, label);
5100 oidcpy(&string_entry->entry.oid, oid);
5101 oidmap_put(&state->commit2label, string_entry);
5103 return string_entry->string;
5106 static int make_script_with_merges(struct pretty_print_context *pp,
5107 struct rev_info *revs, struct strbuf *out,
5108 unsigned flags)
5110 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5111 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5112 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5113 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5114 struct strbuf label = STRBUF_INIT;
5115 struct commit_list *commits = NULL, **tail = &commits, *iter;
5116 struct commit_list *tips = NULL, **tips_tail = &tips;
5117 struct commit *commit;
5118 struct oidmap commit2todo = OIDMAP_INIT;
5119 struct string_entry *entry;
5120 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5121 shown = OIDSET_INIT;
5122 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5124 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5125 const char *cmd_pick = abbr ? "p" : "pick",
5126 *cmd_label = abbr ? "l" : "label",
5127 *cmd_reset = abbr ? "t" : "reset",
5128 *cmd_merge = abbr ? "m" : "merge";
5130 oidmap_init(&commit2todo, 0);
5131 oidmap_init(&state.commit2label, 0);
5132 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5133 strbuf_init(&state.buf, 32);
5135 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5136 struct labels_entry *onto_label_entry;
5137 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5138 FLEX_ALLOC_STR(entry, string, "onto");
5139 oidcpy(&entry->entry.oid, oid);
5140 oidmap_put(&state.commit2label, entry);
5142 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5143 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5144 hashmap_add(&state.labels, &onto_label_entry->entry);
5148 * First phase:
5149 * - get onelines for all commits
5150 * - gather all branch tips (i.e. 2nd or later parents of merges)
5151 * - label all branch tips
5153 while ((commit = get_revision(revs))) {
5154 struct commit_list *to_merge;
5155 const char *p1, *p2;
5156 struct object_id *oid;
5157 int is_empty;
5159 tail = &commit_list_insert(commit, tail)->next;
5160 oidset_insert(&interesting, &commit->object.oid);
5162 is_empty = is_original_commit_empty(commit);
5163 if (!is_empty && (commit->object.flags & PATCHSAME))
5164 continue;
5165 if (is_empty && !keep_empty)
5166 continue;
5168 strbuf_reset(&oneline);
5169 pretty_print_commit(pp, commit, &oneline);
5171 to_merge = commit->parents ? commit->parents->next : NULL;
5172 if (!to_merge) {
5173 /* non-merge commit: easy case */
5174 strbuf_reset(&buf);
5175 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5176 oid_to_hex(&commit->object.oid),
5177 oneline.buf);
5178 if (is_empty)
5179 strbuf_addf(&buf, " %c empty",
5180 comment_line_char);
5182 FLEX_ALLOC_STR(entry, string, buf.buf);
5183 oidcpy(&entry->entry.oid, &commit->object.oid);
5184 oidmap_put(&commit2todo, entry);
5186 continue;
5189 /* Create a label */
5190 strbuf_reset(&label);
5191 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5192 (p1 = strchr(p1, '\'')) &&
5193 (p2 = strchr(++p1, '\'')))
5194 strbuf_add(&label, p1, p2 - p1);
5195 else if (skip_prefix(oneline.buf, "Merge pull request ",
5196 &p1) &&
5197 (p1 = strstr(p1, " from ")))
5198 strbuf_addstr(&label, p1 + strlen(" from "));
5199 else
5200 strbuf_addbuf(&label, &oneline);
5202 strbuf_reset(&buf);
5203 strbuf_addf(&buf, "%s -C %s",
5204 cmd_merge, oid_to_hex(&commit->object.oid));
5206 /* label the tips of merged branches */
5207 for (; to_merge; to_merge = to_merge->next) {
5208 oid = &to_merge->item->object.oid;
5209 strbuf_addch(&buf, ' ');
5211 if (!oidset_contains(&interesting, oid)) {
5212 strbuf_addstr(&buf, label_oid(oid, NULL,
5213 &state));
5214 continue;
5217 tips_tail = &commit_list_insert(to_merge->item,
5218 tips_tail)->next;
5220 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5222 strbuf_addf(&buf, " # %s", oneline.buf);
5224 FLEX_ALLOC_STR(entry, string, buf.buf);
5225 oidcpy(&entry->entry.oid, &commit->object.oid);
5226 oidmap_put(&commit2todo, entry);
5230 * Second phase:
5231 * - label branch points
5232 * - add HEAD to the branch tips
5234 for (iter = commits; iter; iter = iter->next) {
5235 struct commit_list *parent = iter->item->parents;
5236 for (; parent; parent = parent->next) {
5237 struct object_id *oid = &parent->item->object.oid;
5238 if (!oidset_contains(&interesting, oid))
5239 continue;
5240 if (oidset_insert(&child_seen, oid))
5241 label_oid(oid, "branch-point", &state);
5244 /* Add HEAD as implicit "tip of branch" */
5245 if (!iter->next)
5246 tips_tail = &commit_list_insert(iter->item,
5247 tips_tail)->next;
5251 * Third phase: output the todo list. This is a bit tricky, as we
5252 * want to avoid jumping back and forth between revisions. To
5253 * accomplish that goal, we walk backwards from the branch tips,
5254 * gathering commits not yet shown, reversing the list on the fly,
5255 * then outputting that list (labeling revisions as needed).
5257 strbuf_addf(out, "%s onto\n", cmd_label);
5258 for (iter = tips; iter; iter = iter->next) {
5259 struct commit_list *list = NULL, *iter2;
5261 commit = iter->item;
5262 if (oidset_contains(&shown, &commit->object.oid))
5263 continue;
5264 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5266 if (entry)
5267 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5268 else
5269 strbuf_addch(out, '\n');
5271 while (oidset_contains(&interesting, &commit->object.oid) &&
5272 !oidset_contains(&shown, &commit->object.oid)) {
5273 commit_list_insert(commit, &list);
5274 if (!commit->parents) {
5275 commit = NULL;
5276 break;
5278 commit = commit->parents->item;
5281 if (!commit)
5282 strbuf_addf(out, "%s %s\n", cmd_reset,
5283 rebase_cousins || root_with_onto ?
5284 "onto" : "[new root]");
5285 else {
5286 const char *to = NULL;
5288 entry = oidmap_get(&state.commit2label,
5289 &commit->object.oid);
5290 if (entry)
5291 to = entry->string;
5292 else if (!rebase_cousins)
5293 to = label_oid(&commit->object.oid, NULL,
5294 &state);
5296 if (!to || !strcmp(to, "onto"))
5297 strbuf_addf(out, "%s onto\n", cmd_reset);
5298 else {
5299 strbuf_reset(&oneline);
5300 pretty_print_commit(pp, commit, &oneline);
5301 strbuf_addf(out, "%s %s # %s\n",
5302 cmd_reset, to, oneline.buf);
5306 for (iter2 = list; iter2; iter2 = iter2->next) {
5307 struct object_id *oid = &iter2->item->object.oid;
5308 entry = oidmap_get(&commit2todo, oid);
5309 /* only show if not already upstream */
5310 if (entry)
5311 strbuf_addf(out, "%s\n", entry->string);
5312 entry = oidmap_get(&state.commit2label, oid);
5313 if (entry)
5314 strbuf_addf(out, "%s %s\n",
5315 cmd_label, entry->string);
5316 oidset_insert(&shown, oid);
5319 free_commit_list(list);
5322 free_commit_list(commits);
5323 free_commit_list(tips);
5325 strbuf_release(&label);
5326 strbuf_release(&oneline);
5327 strbuf_release(&buf);
5329 oidmap_free(&commit2todo, 1);
5330 oidmap_free(&state.commit2label, 1);
5331 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5332 strbuf_release(&state.buf);
5334 return 0;
5337 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5338 const char **argv, unsigned flags)
5340 char *format = NULL;
5341 struct pretty_print_context pp = {0};
5342 struct rev_info revs;
5343 struct commit *commit;
5344 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5345 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5346 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5347 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5349 repo_init_revisions(r, &revs, NULL);
5350 revs.verbose_header = 1;
5351 if (!rebase_merges)
5352 revs.max_parents = 1;
5353 revs.cherry_mark = !reapply_cherry_picks;
5354 revs.limited = 1;
5355 revs.reverse = 1;
5356 revs.right_only = 1;
5357 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5358 revs.topo_order = 1;
5360 revs.pretty_given = 1;
5361 git_config_get_string("rebase.instructionFormat", &format);
5362 if (!format || !*format) {
5363 free(format);
5364 format = xstrdup("%s");
5366 get_commit_format(format, &revs);
5367 free(format);
5368 pp.fmt = revs.commit_format;
5369 pp.output_encoding = get_log_output_encoding();
5371 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5372 return error(_("make_script: unhandled options"));
5374 if (prepare_revision_walk(&revs) < 0)
5375 return error(_("make_script: error preparing revisions"));
5377 if (rebase_merges)
5378 return make_script_with_merges(&pp, &revs, out, flags);
5380 while ((commit = get_revision(&revs))) {
5381 int is_empty = is_original_commit_empty(commit);
5383 if (!is_empty && (commit->object.flags & PATCHSAME))
5384 continue;
5385 if (is_empty && !keep_empty)
5386 continue;
5387 strbuf_addf(out, "%s %s ", insn,
5388 oid_to_hex(&commit->object.oid));
5389 pretty_print_commit(&pp, commit, out);
5390 if (is_empty)
5391 strbuf_addf(out, " %c empty", comment_line_char);
5392 strbuf_addch(out, '\n');
5394 return 0;
5398 * Add commands after pick and (series of) squash/fixup commands
5399 * in the todo list.
5401 void todo_list_add_exec_commands(struct todo_list *todo_list,
5402 struct string_list *commands)
5404 struct strbuf *buf = &todo_list->buf;
5405 size_t base_offset = buf->len;
5406 int i, insert, nr = 0, alloc = 0;
5407 struct todo_item *items = NULL, *base_items = NULL;
5409 CALLOC_ARRAY(base_items, commands->nr);
5410 for (i = 0; i < commands->nr; i++) {
5411 size_t command_len = strlen(commands->items[i].string);
5413 strbuf_addstr(buf, commands->items[i].string);
5414 strbuf_addch(buf, '\n');
5416 base_items[i].command = TODO_EXEC;
5417 base_items[i].offset_in_buf = base_offset;
5418 base_items[i].arg_offset = base_offset + strlen("exec ");
5419 base_items[i].arg_len = command_len - strlen("exec ");
5421 base_offset += command_len + 1;
5425 * Insert <commands> after every pick. Here, fixup/squash chains
5426 * are considered part of the pick, so we insert the commands *after*
5427 * those chains if there are any.
5429 * As we insert the exec commands immediately after rearranging
5430 * any fixups and before the user edits the list, a fixup chain
5431 * can never contain comments (any comments are empty picks that
5432 * have been commented out because the user did not specify
5433 * --keep-empty). So, it is safe to insert an exec command
5434 * without looking at the command following a comment.
5436 insert = 0;
5437 for (i = 0; i < todo_list->nr; i++) {
5438 enum todo_command command = todo_list->items[i].command;
5439 if (insert && !is_fixup(command)) {
5440 ALLOC_GROW(items, nr + commands->nr, alloc);
5441 COPY_ARRAY(items + nr, base_items, commands->nr);
5442 nr += commands->nr;
5444 insert = 0;
5447 ALLOC_GROW(items, nr + 1, alloc);
5448 items[nr++] = todo_list->items[i];
5450 if (command == TODO_PICK || command == TODO_MERGE)
5451 insert = 1;
5454 /* insert or append final <commands> */
5455 if (insert || nr == todo_list->nr) {
5456 ALLOC_GROW(items, nr + commands->nr, alloc);
5457 COPY_ARRAY(items + nr, base_items, commands->nr);
5458 nr += commands->nr;
5461 free(base_items);
5462 FREE_AND_NULL(todo_list->items);
5463 todo_list->items = items;
5464 todo_list->nr = nr;
5465 todo_list->alloc = alloc;
5468 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5469 struct strbuf *buf, int num, unsigned flags)
5471 struct todo_item *item;
5472 int i, max = todo_list->nr;
5474 if (num > 0 && num < max)
5475 max = num;
5477 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5478 char cmd;
5480 /* if the item is not a command write it and continue */
5481 if (item->command >= TODO_COMMENT) {
5482 strbuf_addf(buf, "%.*s\n", item->arg_len,
5483 todo_item_get_arg(todo_list, item));
5484 continue;
5487 /* add command to the buffer */
5488 cmd = command_to_char(item->command);
5489 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5490 strbuf_addch(buf, cmd);
5491 else
5492 strbuf_addstr(buf, command_to_string(item->command));
5494 /* add commit id */
5495 if (item->commit) {
5496 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5497 short_commit_name(item->commit) :
5498 oid_to_hex(&item->commit->object.oid);
5500 if (item->command == TODO_FIXUP) {
5501 if (item->flags & TODO_EDIT_FIXUP_MSG)
5502 strbuf_addstr(buf, " -c");
5503 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5504 strbuf_addstr(buf, " -C");
5508 if (item->command == TODO_MERGE) {
5509 if (item->flags & TODO_EDIT_MERGE_MSG)
5510 strbuf_addstr(buf, " -c");
5511 else
5512 strbuf_addstr(buf, " -C");
5515 strbuf_addf(buf, " %s", oid);
5518 /* add all the rest */
5519 if (!item->arg_len)
5520 strbuf_addch(buf, '\n');
5521 else
5522 strbuf_addf(buf, " %.*s\n", item->arg_len,
5523 todo_item_get_arg(todo_list, item));
5527 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5528 const char *file, const char *shortrevisions,
5529 const char *shortonto, int num, unsigned flags)
5531 int res;
5532 struct strbuf buf = STRBUF_INIT;
5534 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5535 if (flags & TODO_LIST_APPEND_TODO_HELP)
5536 append_todo_help(count_commands(todo_list),
5537 shortrevisions, shortonto, &buf);
5539 res = write_message(buf.buf, buf.len, file, 0);
5540 strbuf_release(&buf);
5542 return res;
5545 /* skip picking commits whose parents are unchanged */
5546 static int skip_unnecessary_picks(struct repository *r,
5547 struct todo_list *todo_list,
5548 struct object_id *base_oid)
5550 struct object_id *parent_oid;
5551 int i;
5553 for (i = 0; i < todo_list->nr; i++) {
5554 struct todo_item *item = todo_list->items + i;
5556 if (item->command >= TODO_NOOP)
5557 continue;
5558 if (item->command != TODO_PICK)
5559 break;
5560 if (parse_commit(item->commit)) {
5561 return error(_("could not parse commit '%s'"),
5562 oid_to_hex(&item->commit->object.oid));
5564 if (!item->commit->parents)
5565 break; /* root commit */
5566 if (item->commit->parents->next)
5567 break; /* merge commit */
5568 parent_oid = &item->commit->parents->item->object.oid;
5569 if (!oideq(parent_oid, base_oid))
5570 break;
5571 oidcpy(base_oid, &item->commit->object.oid);
5573 if (i > 0) {
5574 const char *done_path = rebase_path_done();
5576 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5577 error_errno(_("could not write to '%s'"), done_path);
5578 return -1;
5581 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5582 todo_list->nr -= i;
5583 todo_list->current = 0;
5584 todo_list->done_nr += i;
5586 if (is_fixup(peek_command(todo_list, 0)))
5587 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5590 return 0;
5593 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5594 const char *shortrevisions, const char *onto_name,
5595 struct commit *onto, const struct object_id *orig_head,
5596 struct string_list *commands, unsigned autosquash,
5597 struct todo_list *todo_list)
5599 char shortonto[GIT_MAX_HEXSZ + 1];
5600 const char *todo_file = rebase_path_todo();
5601 struct todo_list new_todo = TODO_LIST_INIT;
5602 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5603 struct object_id oid = onto->object.oid;
5604 int res;
5606 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5608 if (buf->len == 0) {
5609 struct todo_item *item = append_new_todo(todo_list);
5610 item->command = TODO_NOOP;
5611 item->commit = NULL;
5612 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5615 if (autosquash && todo_list_rearrange_squash(todo_list))
5616 return -1;
5618 if (commands->nr)
5619 todo_list_add_exec_commands(todo_list, commands);
5621 if (count_commands(todo_list) == 0) {
5622 apply_autostash(rebase_path_autostash());
5623 sequencer_remove_state(opts);
5625 return error(_("nothing to do"));
5628 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5629 shortonto, flags);
5630 if (res == -1)
5631 return -1;
5632 else if (res == -2) {
5633 apply_autostash(rebase_path_autostash());
5634 sequencer_remove_state(opts);
5636 return -1;
5637 } else if (res == -3) {
5638 apply_autostash(rebase_path_autostash());
5639 sequencer_remove_state(opts);
5640 todo_list_release(&new_todo);
5642 return error(_("nothing to do"));
5643 } else if (res == -4) {
5644 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5645 todo_list_release(&new_todo);
5647 return -1;
5650 /* Expand the commit IDs */
5651 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5652 strbuf_swap(&new_todo.buf, &buf2);
5653 strbuf_release(&buf2);
5654 new_todo.total_nr -= new_todo.nr;
5655 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5656 BUG("invalid todo list after expanding IDs:\n%s",
5657 new_todo.buf.buf);
5659 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5660 todo_list_release(&new_todo);
5661 return error(_("could not skip unnecessary pick commands"));
5664 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5665 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5666 todo_list_release(&new_todo);
5667 return error_errno(_("could not write '%s'"), todo_file);
5670 res = -1;
5672 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5673 goto cleanup;
5675 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5676 goto cleanup;
5678 todo_list_write_total_nr(&new_todo);
5679 res = pick_commits(r, &new_todo, opts);
5681 cleanup:
5682 todo_list_release(&new_todo);
5684 return res;
5687 struct subject2item_entry {
5688 struct hashmap_entry entry;
5689 int i;
5690 char subject[FLEX_ARRAY];
5693 static int subject2item_cmp(const void *fndata,
5694 const struct hashmap_entry *eptr,
5695 const struct hashmap_entry *entry_or_key,
5696 const void *key)
5698 const struct subject2item_entry *a, *b;
5700 a = container_of(eptr, const struct subject2item_entry, entry);
5701 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5703 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5706 define_commit_slab(commit_todo_item, struct todo_item *);
5708 static int skip_fixupish(const char *subject, const char **p) {
5709 return skip_prefix(subject, "fixup! ", p) ||
5710 skip_prefix(subject, "amend! ", p) ||
5711 skip_prefix(subject, "squash! ", p);
5715 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5716 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5717 * after the former, and change "pick" to "fixup"/"squash".
5719 * Note that if the config has specified a custom instruction format, each log
5720 * message will have to be retrieved from the commit (as the oneline in the
5721 * script cannot be trusted) in order to normalize the autosquash arrangement.
5723 int todo_list_rearrange_squash(struct todo_list *todo_list)
5725 struct hashmap subject2item;
5726 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5727 char **subjects;
5728 struct commit_todo_item commit_todo;
5729 struct todo_item *items = NULL;
5731 init_commit_todo_item(&commit_todo);
5733 * The hashmap maps onelines to the respective todo list index.
5735 * If any items need to be rearranged, the next[i] value will indicate
5736 * which item was moved directly after the i'th.
5738 * In that case, last[i] will indicate the index of the latest item to
5739 * be moved to appear after the i'th.
5741 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5742 ALLOC_ARRAY(next, todo_list->nr);
5743 ALLOC_ARRAY(tail, todo_list->nr);
5744 ALLOC_ARRAY(subjects, todo_list->nr);
5745 for (i = 0; i < todo_list->nr; i++) {
5746 struct strbuf buf = STRBUF_INIT;
5747 struct todo_item *item = todo_list->items + i;
5748 const char *commit_buffer, *subject, *p;
5749 size_t subject_len;
5750 int i2 = -1;
5751 struct subject2item_entry *entry;
5753 next[i] = tail[i] = -1;
5754 if (!item->commit || item->command == TODO_DROP) {
5755 subjects[i] = NULL;
5756 continue;
5759 if (is_fixup(item->command)) {
5760 clear_commit_todo_item(&commit_todo);
5761 return error(_("the script was already rearranged."));
5764 *commit_todo_item_at(&commit_todo, item->commit) = item;
5766 parse_commit(item->commit);
5767 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5768 find_commit_subject(commit_buffer, &subject);
5769 format_subject(&buf, subject, " ");
5770 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5771 unuse_commit_buffer(item->commit, commit_buffer);
5772 if (skip_fixupish(subject, &p)) {
5773 struct commit *commit2;
5775 for (;;) {
5776 while (isspace(*p))
5777 p++;
5778 if (!skip_fixupish(p, &p))
5779 break;
5782 entry = hashmap_get_entry_from_hash(&subject2item,
5783 strhash(p), p,
5784 struct subject2item_entry,
5785 entry);
5786 if (entry)
5787 /* found by title */
5788 i2 = entry->i;
5789 else if (!strchr(p, ' ') &&
5790 (commit2 =
5791 lookup_commit_reference_by_name(p)) &&
5792 *commit_todo_item_at(&commit_todo, commit2))
5793 /* found by commit name */
5794 i2 = *commit_todo_item_at(&commit_todo, commit2)
5795 - todo_list->items;
5796 else {
5797 /* copy can be a prefix of the commit subject */
5798 for (i2 = 0; i2 < i; i2++)
5799 if (subjects[i2] &&
5800 starts_with(subjects[i2], p))
5801 break;
5802 if (i2 == i)
5803 i2 = -1;
5806 if (i2 >= 0) {
5807 rearranged = 1;
5808 if (starts_with(subject, "fixup!")) {
5809 todo_list->items[i].command = TODO_FIXUP;
5810 } else if (starts_with(subject, "amend!")) {
5811 todo_list->items[i].command = TODO_FIXUP;
5812 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5813 } else {
5814 todo_list->items[i].command = TODO_SQUASH;
5816 if (tail[i2] < 0) {
5817 next[i] = next[i2];
5818 next[i2] = i;
5819 } else {
5820 next[i] = next[tail[i2]];
5821 next[tail[i2]] = i;
5823 tail[i2] = i;
5824 } else if (!hashmap_get_from_hash(&subject2item,
5825 strhash(subject), subject)) {
5826 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5827 entry->i = i;
5828 hashmap_entry_init(&entry->entry,
5829 strhash(entry->subject));
5830 hashmap_put(&subject2item, &entry->entry);
5834 if (rearranged) {
5835 for (i = 0; i < todo_list->nr; i++) {
5836 enum todo_command command = todo_list->items[i].command;
5837 int cur = i;
5840 * Initially, all commands are 'pick's. If it is a
5841 * fixup or a squash now, we have rearranged it.
5843 if (is_fixup(command))
5844 continue;
5846 while (cur >= 0) {
5847 ALLOC_GROW(items, nr + 1, alloc);
5848 items[nr++] = todo_list->items[cur];
5849 cur = next[cur];
5853 FREE_AND_NULL(todo_list->items);
5854 todo_list->items = items;
5855 todo_list->nr = nr;
5856 todo_list->alloc = alloc;
5859 free(next);
5860 free(tail);
5861 for (i = 0; i < todo_list->nr; i++)
5862 free(subjects[i]);
5863 free(subjects);
5864 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5866 clear_commit_todo_item(&commit_todo);
5868 return 0;
5871 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5873 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5874 struct object_id cherry_pick_head, rebase_head;
5876 if (file_exists(git_path_seq_dir()))
5877 *whence = FROM_CHERRY_PICK_MULTI;
5878 if (file_exists(rebase_path()) &&
5879 !get_oid("REBASE_HEAD", &rebase_head) &&
5880 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5881 oideq(&rebase_head, &cherry_pick_head))
5882 *whence = FROM_REBASE_PICK;
5883 else
5884 *whence = FROM_CHERRY_PICK_SINGLE;
5886 return 1;
5889 return 0;