git-cvsserver: protect against NULL in crypt(3)
[git.git] / sequencer.c
blob7f07cd00f3f20ab3dc0c508653ac28bdd8e8b8c1
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) && read_env_script(&cmd.env_array)) {
987 const char *gpg_opt = gpg_sign_opt_quoted(opts);
989 return error(_(staged_changes_advice),
990 gpg_opt, gpg_opt);
993 if (opts->committer_date_is_author_date)
994 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
995 opts->ignore_date ?
996 "" :
997 author_date_from_env_array(&cmd.env_array));
998 if (opts->ignore_date)
999 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1001 strvec_push(&cmd.args, "commit");
1003 if (!(flags & VERIFY_MSG))
1004 strvec_push(&cmd.args, "-n");
1005 if ((flags & AMEND_MSG))
1006 strvec_push(&cmd.args, "--amend");
1007 if (opts->gpg_sign)
1008 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1009 else
1010 strvec_push(&cmd.args, "--no-gpg-sign");
1011 if (defmsg)
1012 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1013 else if (!(flags & EDIT_MSG))
1014 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1015 if ((flags & CLEANUP_MSG))
1016 strvec_push(&cmd.args, "--cleanup=strip");
1017 if ((flags & VERBATIM_MSG))
1018 strvec_push(&cmd.args, "--cleanup=verbatim");
1019 if ((flags & EDIT_MSG))
1020 strvec_push(&cmd.args, "-e");
1021 else if (!(flags & CLEANUP_MSG) &&
1022 !opts->signoff && !opts->record_origin &&
1023 !opts->explicit_cleanup)
1024 strvec_push(&cmd.args, "--cleanup=verbatim");
1026 if ((flags & ALLOW_EMPTY))
1027 strvec_push(&cmd.args, "--allow-empty");
1029 if (!(flags & EDIT_MSG))
1030 strvec_push(&cmd.args, "--allow-empty-message");
1032 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1033 return run_command_silent_on_success(&cmd);
1034 else
1035 return run_command(&cmd);
1038 static int rest_is_empty(const struct strbuf *sb, int start)
1040 int i, eol;
1041 const char *nl;
1043 /* Check if the rest is just whitespace and Signed-off-by's. */
1044 for (i = start; i < sb->len; i++) {
1045 nl = memchr(sb->buf + i, '\n', sb->len - i);
1046 if (nl)
1047 eol = nl - sb->buf;
1048 else
1049 eol = sb->len;
1051 if (strlen(sign_off_header) <= eol - i &&
1052 starts_with(sb->buf + i, sign_off_header)) {
1053 i = eol;
1054 continue;
1056 while (i < eol)
1057 if (!isspace(sb->buf[i++]))
1058 return 0;
1061 return 1;
1064 void cleanup_message(struct strbuf *msgbuf,
1065 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1067 if (verbose || /* Truncate the message just before the diff, if any. */
1068 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1069 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1070 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1071 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1075 * Find out if the message in the strbuf contains only whitespace and
1076 * Signed-off-by lines.
1078 int message_is_empty(const struct strbuf *sb,
1079 enum commit_msg_cleanup_mode cleanup_mode)
1081 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1082 return 0;
1083 return rest_is_empty(sb, 0);
1087 * See if the user edited the message in the editor or left what
1088 * was in the template intact
1090 int template_untouched(const struct strbuf *sb, const char *template_file,
1091 enum commit_msg_cleanup_mode cleanup_mode)
1093 struct strbuf tmpl = STRBUF_INIT;
1094 const char *start;
1096 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1097 return 0;
1099 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1100 return 0;
1102 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1103 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1104 start = sb->buf;
1105 strbuf_release(&tmpl);
1106 return rest_is_empty(sb, start - sb->buf);
1109 int update_head_with_reflog(const struct commit *old_head,
1110 const struct object_id *new_head,
1111 const char *action, const struct strbuf *msg,
1112 struct strbuf *err)
1114 struct ref_transaction *transaction;
1115 struct strbuf sb = STRBUF_INIT;
1116 const char *nl;
1117 int ret = 0;
1119 if (action) {
1120 strbuf_addstr(&sb, action);
1121 strbuf_addstr(&sb, ": ");
1124 nl = strchr(msg->buf, '\n');
1125 if (nl) {
1126 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1127 } else {
1128 strbuf_addbuf(&sb, msg);
1129 strbuf_addch(&sb, '\n');
1132 transaction = ref_transaction_begin(err);
1133 if (!transaction ||
1134 ref_transaction_update(transaction, "HEAD", new_head,
1135 old_head ? &old_head->object.oid : null_oid(),
1136 0, sb.buf, err) ||
1137 ref_transaction_commit(transaction, err)) {
1138 ret = -1;
1140 ref_transaction_free(transaction);
1141 strbuf_release(&sb);
1143 return ret;
1146 static int run_rewrite_hook(const struct object_id *oldoid,
1147 const struct object_id *newoid)
1149 struct child_process proc = CHILD_PROCESS_INIT;
1150 const char *argv[3];
1151 int code;
1152 struct strbuf sb = STRBUF_INIT;
1154 argv[0] = find_hook("post-rewrite");
1155 if (!argv[0])
1156 return 0;
1158 argv[1] = "amend";
1159 argv[2] = NULL;
1161 proc.argv = argv;
1162 proc.in = -1;
1163 proc.stdout_to_stderr = 1;
1164 proc.trace2_hook_name = "post-rewrite";
1166 code = start_command(&proc);
1167 if (code)
1168 return code;
1169 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1170 sigchain_push(SIGPIPE, SIG_IGN);
1171 write_in_full(proc.in, sb.buf, sb.len);
1172 close(proc.in);
1173 strbuf_release(&sb);
1174 sigchain_pop(SIGPIPE);
1175 return finish_command(&proc);
1178 void commit_post_rewrite(struct repository *r,
1179 const struct commit *old_head,
1180 const struct object_id *new_head)
1182 struct notes_rewrite_cfg *cfg;
1184 cfg = init_copy_notes_for_rewrite("amend");
1185 if (cfg) {
1186 /* we are amending, so old_head is not NULL */
1187 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1188 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1190 run_rewrite_hook(&old_head->object.oid, new_head);
1193 static int run_prepare_commit_msg_hook(struct repository *r,
1194 struct strbuf *msg,
1195 const char *commit)
1197 int ret = 0;
1198 const char *name, *arg1 = NULL, *arg2 = NULL;
1200 name = git_path_commit_editmsg();
1201 if (write_message(msg->buf, msg->len, name, 0))
1202 return -1;
1204 if (commit) {
1205 arg1 = "commit";
1206 arg2 = commit;
1207 } else {
1208 arg1 = "message";
1210 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1211 arg1, arg2, NULL))
1212 ret = error(_("'prepare-commit-msg' hook failed"));
1214 return ret;
1217 static const char implicit_ident_advice_noconfig[] =
1218 N_("Your name and email address were configured automatically based\n"
1219 "on your username and hostname. Please check that they are accurate.\n"
1220 "You can suppress this message by setting them explicitly. Run the\n"
1221 "following command and follow the instructions in your editor to edit\n"
1222 "your configuration file:\n"
1223 "\n"
1224 " git config --global --edit\n"
1225 "\n"
1226 "After doing this, you may fix the identity used for this commit with:\n"
1227 "\n"
1228 " git commit --amend --reset-author\n");
1230 static const char implicit_ident_advice_config[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly:\n"
1234 "\n"
1235 " git config --global user.name \"Your Name\"\n"
1236 " git config --global user.email you@example.com\n"
1237 "\n"
1238 "After doing this, you may fix the identity used for this commit with:\n"
1239 "\n"
1240 " git commit --amend --reset-author\n");
1242 static const char *implicit_ident_advice(void)
1244 char *user_config = expand_user_path("~/.gitconfig", 0);
1245 char *xdg_config = xdg_config_home("config");
1246 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1248 free(user_config);
1249 free(xdg_config);
1251 if (config_exists)
1252 return _(implicit_ident_advice_config);
1253 else
1254 return _(implicit_ident_advice_noconfig);
1258 void print_commit_summary(struct repository *r,
1259 const char *prefix,
1260 const struct object_id *oid,
1261 unsigned int flags)
1263 struct rev_info rev;
1264 struct commit *commit;
1265 struct strbuf format = STRBUF_INIT;
1266 const char *head;
1267 struct pretty_print_context pctx = {0};
1268 struct strbuf author_ident = STRBUF_INIT;
1269 struct strbuf committer_ident = STRBUF_INIT;
1271 commit = lookup_commit(r, oid);
1272 if (!commit)
1273 die(_("couldn't look up newly created commit"));
1274 if (parse_commit(commit))
1275 die(_("could not parse newly created commit"));
1277 strbuf_addstr(&format, "format:%h] %s");
1279 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1280 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1281 if (strbuf_cmp(&author_ident, &committer_ident)) {
1282 strbuf_addstr(&format, "\n Author: ");
1283 strbuf_addbuf_percentquote(&format, &author_ident);
1285 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1286 struct strbuf date = STRBUF_INIT;
1288 format_commit_message(commit, "%ad", &date, &pctx);
1289 strbuf_addstr(&format, "\n Date: ");
1290 strbuf_addbuf_percentquote(&format, &date);
1291 strbuf_release(&date);
1293 if (!committer_ident_sufficiently_given()) {
1294 strbuf_addstr(&format, "\n Committer: ");
1295 strbuf_addbuf_percentquote(&format, &committer_ident);
1296 if (advice_implicit_identity) {
1297 strbuf_addch(&format, '\n');
1298 strbuf_addstr(&format, implicit_ident_advice());
1301 strbuf_release(&author_ident);
1302 strbuf_release(&committer_ident);
1304 repo_init_revisions(r, &rev, prefix);
1305 setup_revisions(0, NULL, &rev, NULL);
1307 rev.diff = 1;
1308 rev.diffopt.output_format =
1309 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1311 rev.verbose_header = 1;
1312 rev.show_root_diff = 1;
1313 get_commit_format(format.buf, &rev);
1314 rev.always_show_header = 0;
1315 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1316 rev.diffopt.break_opt = 0;
1317 diff_setup_done(&rev.diffopt);
1319 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1320 if (!head)
1321 die_errno(_("unable to resolve HEAD after creating commit"));
1322 if (!strcmp(head, "HEAD"))
1323 head = _("detached HEAD");
1324 else
1325 skip_prefix(head, "refs/heads/", &head);
1326 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1327 _(" (root-commit)") : "");
1329 if (!log_tree_commit(&rev, commit)) {
1330 rev.always_show_header = 1;
1331 rev.use_terminator = 1;
1332 log_tree_commit(&rev, commit);
1335 strbuf_release(&format);
1338 static int parse_head(struct repository *r, struct commit **head)
1340 struct commit *current_head;
1341 struct object_id oid;
1343 if (get_oid("HEAD", &oid)) {
1344 current_head = NULL;
1345 } else {
1346 current_head = lookup_commit_reference(r, &oid);
1347 if (!current_head)
1348 return error(_("could not parse HEAD"));
1349 if (!oideq(&oid, &current_head->object.oid)) {
1350 warning(_("HEAD %s is not a commit!"),
1351 oid_to_hex(&oid));
1353 if (parse_commit(current_head))
1354 return error(_("could not parse HEAD commit"));
1356 *head = current_head;
1358 return 0;
1362 * Try to commit without forking 'git commit'. In some cases we need
1363 * to run 'git commit' to display an error message
1365 * Returns:
1366 * -1 - error unable to commit
1367 * 0 - success
1368 * 1 - run 'git commit'
1370 static int try_to_commit(struct repository *r,
1371 struct strbuf *msg, const char *author,
1372 struct replay_opts *opts, unsigned int flags,
1373 struct object_id *oid)
1375 struct object_id tree;
1376 struct commit *current_head = NULL;
1377 struct commit_list *parents = NULL;
1378 struct commit_extra_header *extra = NULL;
1379 struct strbuf err = STRBUF_INIT;
1380 struct strbuf commit_msg = STRBUF_INIT;
1381 char *amend_author = NULL;
1382 const char *committer = NULL;
1383 const char *hook_commit = NULL;
1384 enum commit_msg_cleanup_mode cleanup;
1385 int res = 0;
1387 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1388 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1390 if (parse_head(r, &current_head))
1391 return -1;
1393 if (flags & AMEND_MSG) {
1394 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1395 const char *out_enc = get_commit_output_encoding();
1396 const char *message = logmsg_reencode(current_head, NULL,
1397 out_enc);
1399 if (!msg) {
1400 const char *orig_message = NULL;
1402 find_commit_subject(message, &orig_message);
1403 msg = &commit_msg;
1404 strbuf_addstr(msg, orig_message);
1405 hook_commit = "HEAD";
1407 author = amend_author = get_author(message);
1408 unuse_commit_buffer(current_head, message);
1409 if (!author) {
1410 res = error(_("unable to parse commit author"));
1411 goto out;
1413 parents = copy_commit_list(current_head->parents);
1414 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1415 } else if (current_head &&
1416 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1417 commit_list_insert(current_head, &parents);
1420 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1421 res = error(_("git write-tree failed to write a tree"));
1422 goto out;
1425 if (!(flags & ALLOW_EMPTY)) {
1426 struct commit *first_parent = current_head;
1428 if (flags & AMEND_MSG) {
1429 if (current_head->parents) {
1430 first_parent = current_head->parents->item;
1431 if (repo_parse_commit(r, first_parent)) {
1432 res = error(_("could not parse HEAD commit"));
1433 goto out;
1435 } else {
1436 first_parent = NULL;
1439 if (oideq(first_parent
1440 ? get_commit_tree_oid(first_parent)
1441 : the_hash_algo->empty_tree,
1442 &tree)) {
1443 res = 1; /* run 'git commit' to display error message */
1444 goto out;
1448 if (find_hook("prepare-commit-msg")) {
1449 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1450 if (res)
1451 goto out;
1452 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1453 2048) < 0) {
1454 res = error_errno(_("unable to read commit message "
1455 "from '%s'"),
1456 git_path_commit_editmsg());
1457 goto out;
1459 msg = &commit_msg;
1462 if (flags & CLEANUP_MSG)
1463 cleanup = COMMIT_MSG_CLEANUP_ALL;
1464 else if (flags & VERBATIM_MSG)
1465 cleanup = COMMIT_MSG_CLEANUP_NONE;
1466 else if ((opts->signoff || opts->record_origin) &&
1467 !opts->explicit_cleanup)
1468 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1469 else
1470 cleanup = opts->default_msg_cleanup;
1472 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1473 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1474 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1475 res = 1; /* run 'git commit' to display error message */
1476 goto out;
1479 if (opts->committer_date_is_author_date) {
1480 struct ident_split id;
1481 struct strbuf date = STRBUF_INIT;
1483 if (!opts->ignore_date) {
1484 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1485 res = error(_("invalid author identity '%s'"),
1486 author);
1487 goto out;
1489 if (!id.date_begin) {
1490 res = error(_(
1491 "corrupt author: missing date information"));
1492 goto out;
1494 strbuf_addf(&date, "@%.*s %.*s",
1495 (int)(id.date_end - id.date_begin),
1496 id.date_begin,
1497 (int)(id.tz_end - id.tz_begin),
1498 id.tz_begin);
1499 } else {
1500 reset_ident_date();
1502 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1503 getenv("GIT_COMMITTER_EMAIL"),
1504 WANT_COMMITTER_IDENT,
1505 opts->ignore_date ? NULL : date.buf,
1506 IDENT_STRICT);
1507 strbuf_release(&date);
1508 } else {
1509 reset_ident_date();
1512 if (opts->ignore_date) {
1513 struct ident_split id;
1514 char *name, *email;
1516 if (split_ident_line(&id, author, strlen(author)) < 0) {
1517 error(_("invalid author identity '%s'"), author);
1518 goto out;
1520 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1521 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1522 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1523 IDENT_STRICT);
1524 free(name);
1525 free(email);
1528 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1529 author, committer, opts->gpg_sign, extra)) {
1530 res = error(_("failed to write commit object"));
1531 goto out;
1534 if (update_head_with_reflog(current_head, oid,
1535 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1536 res = error("%s", err.buf);
1537 goto out;
1540 run_commit_hook(0, r->index_file, "post-commit", NULL);
1541 if (flags & AMEND_MSG)
1542 commit_post_rewrite(r, current_head, oid);
1544 out:
1545 free_commit_extra_headers(extra);
1546 strbuf_release(&err);
1547 strbuf_release(&commit_msg);
1548 free(amend_author);
1550 return res;
1553 static int write_rebase_head(struct object_id *oid)
1555 if (update_ref("rebase", "REBASE_HEAD", oid,
1556 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1557 return error(_("could not update %s"), "REBASE_HEAD");
1559 return 0;
1562 static int do_commit(struct repository *r,
1563 const char *msg_file, const char *author,
1564 struct replay_opts *opts, unsigned int flags,
1565 struct object_id *oid)
1567 int res = 1;
1569 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1570 struct object_id oid;
1571 struct strbuf sb = STRBUF_INIT;
1573 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1574 return error_errno(_("unable to read commit message "
1575 "from '%s'"),
1576 msg_file);
1578 res = try_to_commit(r, msg_file ? &sb : NULL,
1579 author, opts, flags, &oid);
1580 strbuf_release(&sb);
1581 if (!res) {
1582 refs_delete_ref(get_main_ref_store(r), "",
1583 "CHERRY_PICK_HEAD", NULL, 0);
1584 unlink(git_path_merge_msg(r));
1585 if (!is_rebase_i(opts))
1586 print_commit_summary(r, NULL, &oid,
1587 SUMMARY_SHOW_AUTHOR_DATE);
1588 return res;
1591 if (res == 1) {
1592 if (is_rebase_i(opts) && oid)
1593 if (write_rebase_head(oid))
1594 return -1;
1595 return run_git_commit(msg_file, opts, flags);
1598 return res;
1601 static int is_original_commit_empty(struct commit *commit)
1603 const struct object_id *ptree_oid;
1605 if (parse_commit(commit))
1606 return error(_("could not parse commit %s"),
1607 oid_to_hex(&commit->object.oid));
1608 if (commit->parents) {
1609 struct commit *parent = commit->parents->item;
1610 if (parse_commit(parent))
1611 return error(_("could not parse parent commit %s"),
1612 oid_to_hex(&parent->object.oid));
1613 ptree_oid = get_commit_tree_oid(parent);
1614 } else {
1615 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1618 return oideq(ptree_oid, get_commit_tree_oid(commit));
1622 * Should empty commits be allowed? Return status:
1623 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1624 * 0: Halt on empty commit
1625 * 1: Allow empty commit
1626 * 2: Drop empty commit
1628 static int allow_empty(struct repository *r,
1629 struct replay_opts *opts,
1630 struct commit *commit)
1632 int index_unchanged, originally_empty;
1635 * Four cases:
1637 * (1) we do not allow empty at all and error out.
1639 * (2) we allow ones that were initially empty, and
1640 * just drop the ones that become empty
1642 * (3) we allow ones that were initially empty, but
1643 * halt for the ones that become empty;
1645 * (4) we allow both.
1647 if (!opts->allow_empty)
1648 return 0; /* let "git commit" barf as necessary */
1650 index_unchanged = is_index_unchanged(r);
1651 if (index_unchanged < 0)
1652 return index_unchanged;
1653 if (!index_unchanged)
1654 return 0; /* we do not have to say --allow-empty */
1656 if (opts->keep_redundant_commits)
1657 return 1;
1659 originally_empty = is_original_commit_empty(commit);
1660 if (originally_empty < 0)
1661 return originally_empty;
1662 if (originally_empty)
1663 return 1;
1664 else if (opts->drop_redundant_commits)
1665 return 2;
1666 else
1667 return 0;
1670 static struct {
1671 char c;
1672 const char *str;
1673 } todo_command_info[] = {
1674 { 'p', "pick" },
1675 { 0, "revert" },
1676 { 'e', "edit" },
1677 { 'r', "reword" },
1678 { 'f', "fixup" },
1679 { 's', "squash" },
1680 { 'x', "exec" },
1681 { 'b', "break" },
1682 { 'l', "label" },
1683 { 't', "reset" },
1684 { 'm', "merge" },
1685 { 0, "noop" },
1686 { 'd', "drop" },
1687 { 0, NULL }
1690 static const char *command_to_string(const enum todo_command command)
1692 if (command < TODO_COMMENT)
1693 return todo_command_info[command].str;
1694 die(_("unknown command: %d"), command);
1697 static char command_to_char(const enum todo_command command)
1699 if (command < TODO_COMMENT)
1700 return todo_command_info[command].c;
1701 return comment_line_char;
1704 static int is_noop(const enum todo_command command)
1706 return TODO_NOOP <= command;
1709 static int is_fixup(enum todo_command command)
1711 return command == TODO_FIXUP || command == TODO_SQUASH;
1714 /* Does this command create a (non-merge) commit? */
1715 static int is_pick_or_similar(enum todo_command command)
1717 switch (command) {
1718 case TODO_PICK:
1719 case TODO_REVERT:
1720 case TODO_EDIT:
1721 case TODO_REWORD:
1722 case TODO_FIXUP:
1723 case TODO_SQUASH:
1724 return 1;
1725 default:
1726 return 0;
1730 enum todo_item_flags {
1731 TODO_EDIT_MERGE_MSG = (1 << 0),
1732 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1733 TODO_EDIT_FIXUP_MSG = (1 << 2),
1736 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1737 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1738 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1739 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1740 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1742 static int is_fixup_flag(enum todo_command command, unsigned flag)
1744 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1745 (flag & TODO_EDIT_FIXUP_MSG));
1749 * Wrapper around strbuf_add_commented_lines() which avoids double
1750 * commenting commit subjects.
1752 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1754 const char *s = str;
1755 while (len > 0 && s[0] == comment_line_char) {
1756 size_t count;
1757 const char *n = memchr(s, '\n', len);
1758 if (!n)
1759 count = len;
1760 else
1761 count = n - s + 1;
1762 strbuf_add(buf, s, count);
1763 s += count;
1764 len -= count;
1766 strbuf_add_commented_lines(buf, s, len);
1769 /* Does the current fixup chain contain a squash command? */
1770 static int seen_squash(struct replay_opts *opts)
1772 return starts_with(opts->current_fixups.buf, "squash") ||
1773 strstr(opts->current_fixups.buf, "\nsquash");
1776 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1778 strbuf_setlen(buf1, 2);
1779 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1780 strbuf_addch(buf1, '\n');
1781 strbuf_setlen(buf2, 2);
1782 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1783 strbuf_addch(buf2, '\n');
1787 * Comment out any un-commented commit messages, updating the message comments
1788 * to say they will be skipped but do not comment out the empty lines that
1789 * surround commit messages and their comments.
1791 static void update_squash_message_for_fixup(struct strbuf *msg)
1793 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1794 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1795 const char *s, *start;
1796 char *orig_msg;
1797 size_t orig_msg_len;
1798 int i = 1;
1800 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1801 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1802 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1803 while (s) {
1804 const char *next;
1805 size_t off;
1806 if (skip_prefix(s, buf1.buf, &next)) {
1808 * Copy the last message, preserving the blank line
1809 * preceding the current line
1811 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1812 copy_lines(msg, start, s - start - off);
1813 if (off)
1814 strbuf_addch(msg, '\n');
1816 * The next message needs to be commented out but the
1817 * message header is already commented out so just copy
1818 * it and the blank line that follows it.
1820 strbuf_addbuf(msg, &buf2);
1821 if (*next == '\n')
1822 strbuf_addch(msg, *next++);
1823 start = s = next;
1824 copy_lines = add_commented_lines;
1825 update_comment_bufs(&buf1, &buf2, ++i);
1826 } else if (skip_prefix(s, buf2.buf, &next)) {
1827 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1828 copy_lines(msg, start, s - start - off);
1829 start = s - off;
1830 s = next;
1831 copy_lines = strbuf_add;
1832 update_comment_bufs(&buf1, &buf2, ++i);
1833 } else {
1834 s = strchr(s, '\n');
1835 if (s)
1836 s++;
1839 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1840 free(orig_msg);
1841 strbuf_release(&buf1);
1842 strbuf_release(&buf2);
1845 static int append_squash_message(struct strbuf *buf, const char *body,
1846 enum todo_command command, struct replay_opts *opts,
1847 unsigned flag)
1849 const char *fixup_msg;
1850 size_t commented_len = 0, fixup_off;
1852 * amend is non-interactive and not normally used with fixup!
1853 * or squash! commits, so only comment out those subjects when
1854 * squashing commit messages.
1856 if (starts_with(body, "amend!") ||
1857 ((command == TODO_SQUASH || seen_squash(opts)) &&
1858 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1859 commented_len = commit_subject_length(body);
1861 strbuf_addf(buf, "\n%c ", comment_line_char);
1862 strbuf_addf(buf, _(nth_commit_msg_fmt),
1863 ++opts->current_fixup_count + 1);
1864 strbuf_addstr(buf, "\n\n");
1865 strbuf_add_commented_lines(buf, body, commented_len);
1866 /* buf->buf may be reallocated so store an offset into the buffer */
1867 fixup_off = buf->len;
1868 strbuf_addstr(buf, body + commented_len);
1870 /* fixup -C after squash behaves like squash */
1871 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1873 * We're replacing the commit message so we need to
1874 * append the Signed-off-by: trailer if the user
1875 * requested '--signoff'.
1877 if (opts->signoff)
1878 append_signoff(buf, 0, 0);
1880 if ((command == TODO_FIXUP) &&
1881 (flag & TODO_REPLACE_FIXUP_MSG) &&
1882 (file_exists(rebase_path_fixup_msg()) ||
1883 !file_exists(rebase_path_squash_msg()))) {
1884 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1885 if (write_message(fixup_msg, strlen(fixup_msg),
1886 rebase_path_fixup_msg(), 0) < 0)
1887 return error(_("cannot write '%s'"),
1888 rebase_path_fixup_msg());
1889 } else {
1890 unlink(rebase_path_fixup_msg());
1892 } else {
1893 unlink(rebase_path_fixup_msg());
1896 return 0;
1899 static int update_squash_messages(struct repository *r,
1900 enum todo_command command,
1901 struct commit *commit,
1902 struct replay_opts *opts,
1903 unsigned flag)
1905 struct strbuf buf = STRBUF_INIT;
1906 int res = 0;
1907 const char *message, *body;
1908 const char *encoding = get_commit_output_encoding();
1910 if (opts->current_fixup_count > 0) {
1911 struct strbuf header = STRBUF_INIT;
1912 char *eol;
1914 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1915 return error(_("could not read '%s'"),
1916 rebase_path_squash_msg());
1918 eol = buf.buf[0] != comment_line_char ?
1919 buf.buf : strchrnul(buf.buf, '\n');
1921 strbuf_addf(&header, "%c ", comment_line_char);
1922 strbuf_addf(&header, _(combined_commit_msg_fmt),
1923 opts->current_fixup_count + 2);
1924 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1925 strbuf_release(&header);
1926 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1927 update_squash_message_for_fixup(&buf);
1928 } else {
1929 struct object_id head;
1930 struct commit *head_commit;
1931 const char *head_message, *body;
1933 if (get_oid("HEAD", &head))
1934 return error(_("need a HEAD to fixup"));
1935 if (!(head_commit = lookup_commit_reference(r, &head)))
1936 return error(_("could not read HEAD"));
1937 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1938 return error(_("could not read HEAD's commit message"));
1940 find_commit_subject(head_message, &body);
1941 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1942 rebase_path_fixup_msg(), 0) < 0) {
1943 unuse_commit_buffer(head_commit, head_message);
1944 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1946 strbuf_addf(&buf, "%c ", comment_line_char);
1947 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1948 strbuf_addf(&buf, "\n%c ", comment_line_char);
1949 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1950 _(skip_first_commit_msg_str) :
1951 _(first_commit_msg_str));
1952 strbuf_addstr(&buf, "\n\n");
1953 if (is_fixup_flag(command, flag))
1954 strbuf_add_commented_lines(&buf, body, strlen(body));
1955 else
1956 strbuf_addstr(&buf, body);
1958 unuse_commit_buffer(head_commit, head_message);
1961 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1962 return error(_("could not read commit message of %s"),
1963 oid_to_hex(&commit->object.oid));
1964 find_commit_subject(message, &body);
1966 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1967 res = append_squash_message(&buf, body, command, opts, flag);
1968 } else if (command == TODO_FIXUP) {
1969 strbuf_addf(&buf, "\n%c ", comment_line_char);
1970 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1971 ++opts->current_fixup_count + 1);
1972 strbuf_addstr(&buf, "\n\n");
1973 strbuf_add_commented_lines(&buf, body, strlen(body));
1974 } else
1975 return error(_("unknown command: %d"), command);
1976 unuse_commit_buffer(commit, message);
1978 if (!res)
1979 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1981 strbuf_release(&buf);
1983 if (!res) {
1984 strbuf_addf(&opts->current_fixups, "%s%s %s",
1985 opts->current_fixups.len ? "\n" : "",
1986 command_to_string(command),
1987 oid_to_hex(&commit->object.oid));
1988 res = write_message(opts->current_fixups.buf,
1989 opts->current_fixups.len,
1990 rebase_path_current_fixups(), 0);
1993 return res;
1996 static void flush_rewritten_pending(void)
1998 struct strbuf buf = STRBUF_INIT;
1999 struct object_id newoid;
2000 FILE *out;
2002 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2003 !get_oid("HEAD", &newoid) &&
2004 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2005 char *bol = buf.buf, *eol;
2007 while (*bol) {
2008 eol = strchrnul(bol, '\n');
2009 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2010 bol, oid_to_hex(&newoid));
2011 if (!*eol)
2012 break;
2013 bol = eol + 1;
2015 fclose(out);
2016 unlink(rebase_path_rewritten_pending());
2018 strbuf_release(&buf);
2021 static void record_in_rewritten(struct object_id *oid,
2022 enum todo_command next_command)
2024 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2026 if (!out)
2027 return;
2029 fprintf(out, "%s\n", oid_to_hex(oid));
2030 fclose(out);
2032 if (!is_fixup(next_command))
2033 flush_rewritten_pending();
2036 static int should_edit(struct replay_opts *opts) {
2037 if (opts->edit < 0)
2039 * Note that we only handle the case of non-conflicted
2040 * commits; continue_single_pick() handles the conflicted
2041 * commits itself instead of calling this function.
2043 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2044 return opts->edit;
2047 static int do_pick_commit(struct repository *r,
2048 struct todo_item *item,
2049 struct replay_opts *opts,
2050 int final_fixup, int *check_todo)
2052 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2053 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2054 struct object_id head;
2055 struct commit *base, *next, *parent;
2056 const char *base_label, *next_label;
2057 char *author = NULL;
2058 struct commit_message msg = { NULL, NULL, NULL, NULL };
2059 struct strbuf msgbuf = STRBUF_INIT;
2060 int res, unborn = 0, reword = 0, allow, drop_commit;
2061 enum todo_command command = item->command;
2062 struct commit *commit = item->commit;
2064 if (opts->no_commit) {
2066 * We do not intend to commit immediately. We just want to
2067 * merge the differences in, so let's compute the tree
2068 * that represents the "current" state for merge-recursive
2069 * to work on.
2071 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2072 return error(_("your index file is unmerged."));
2073 } else {
2074 unborn = get_oid("HEAD", &head);
2075 /* Do we want to generate a root commit? */
2076 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2077 oideq(&head, &opts->squash_onto)) {
2078 if (is_fixup(command))
2079 return error(_("cannot fixup root commit"));
2080 flags |= CREATE_ROOT_COMMIT;
2081 unborn = 1;
2082 } else if (unborn)
2083 oidcpy(&head, the_hash_algo->empty_tree);
2084 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2085 NULL, 0))
2086 return error_dirty_index(r, opts);
2088 discard_index(r->index);
2090 if (!commit->parents)
2091 parent = NULL;
2092 else if (commit->parents->next) {
2093 /* Reverting or cherry-picking a merge commit */
2094 int cnt;
2095 struct commit_list *p;
2097 if (!opts->mainline)
2098 return error(_("commit %s is a merge but no -m option was given."),
2099 oid_to_hex(&commit->object.oid));
2101 for (cnt = 1, p = commit->parents;
2102 cnt != opts->mainline && p;
2103 cnt++)
2104 p = p->next;
2105 if (cnt != opts->mainline || !p)
2106 return error(_("commit %s does not have parent %d"),
2107 oid_to_hex(&commit->object.oid), opts->mainline);
2108 parent = p->item;
2109 } else if (1 < opts->mainline)
2111 * Non-first parent explicitly specified as mainline for
2112 * non-merge commit
2114 return error(_("commit %s does not have parent %d"),
2115 oid_to_hex(&commit->object.oid), opts->mainline);
2116 else
2117 parent = commit->parents->item;
2119 if (get_message(commit, &msg) != 0)
2120 return error(_("cannot get commit message for %s"),
2121 oid_to_hex(&commit->object.oid));
2123 if (opts->allow_ff && !is_fixup(command) &&
2124 ((parent && oideq(&parent->object.oid, &head)) ||
2125 (!parent && unborn))) {
2126 if (is_rebase_i(opts))
2127 write_author_script(msg.message);
2128 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2129 opts);
2130 if (res || command != TODO_REWORD)
2131 goto leave;
2132 reword = 1;
2133 msg_file = NULL;
2134 goto fast_forward_edit;
2136 if (parent && parse_commit(parent) < 0)
2137 /* TRANSLATORS: The first %s will be a "todo" command like
2138 "revert" or "pick", the second %s a SHA1. */
2139 return error(_("%s: cannot parse parent commit %s"),
2140 command_to_string(command),
2141 oid_to_hex(&parent->object.oid));
2144 * "commit" is an existing commit. We would want to apply
2145 * the difference it introduces since its first parent "prev"
2146 * on top of the current HEAD if we are cherry-pick. Or the
2147 * reverse of it if we are revert.
2150 if (command == TODO_REVERT) {
2151 base = commit;
2152 base_label = msg.label;
2153 next = parent;
2154 next_label = msg.parent_label;
2155 strbuf_addstr(&msgbuf, "Revert \"");
2156 strbuf_addstr(&msgbuf, msg.subject);
2157 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2158 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2160 if (commit->parents && commit->parents->next) {
2161 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2162 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2164 strbuf_addstr(&msgbuf, ".\n");
2165 } else {
2166 const char *p;
2168 base = parent;
2169 base_label = msg.parent_label;
2170 next = commit;
2171 next_label = msg.label;
2173 /* Append the commit log message to msgbuf. */
2174 if (find_commit_subject(msg.message, &p))
2175 strbuf_addstr(&msgbuf, p);
2177 if (opts->record_origin) {
2178 strbuf_complete_line(&msgbuf);
2179 if (!has_conforming_footer(&msgbuf, NULL, 0))
2180 strbuf_addch(&msgbuf, '\n');
2181 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2182 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2183 strbuf_addstr(&msgbuf, ")\n");
2185 if (!is_fixup(command))
2186 author = get_author(msg.message);
2189 if (command == TODO_REWORD)
2190 reword = 1;
2191 else if (is_fixup(command)) {
2192 if (update_squash_messages(r, command, commit,
2193 opts, item->flags))
2194 return -1;
2195 flags |= AMEND_MSG;
2196 if (!final_fixup)
2197 msg_file = rebase_path_squash_msg();
2198 else if (file_exists(rebase_path_fixup_msg())) {
2199 flags |= VERBATIM_MSG;
2200 msg_file = rebase_path_fixup_msg();
2201 } else {
2202 const char *dest = git_path_squash_msg(r);
2203 unlink(dest);
2204 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2205 return error(_("could not rename '%s' to '%s'"),
2206 rebase_path_squash_msg(), dest);
2207 unlink(git_path_merge_msg(r));
2208 msg_file = dest;
2209 flags |= EDIT_MSG;
2213 if (opts->signoff && !is_fixup(command))
2214 append_signoff(&msgbuf, 0, 0);
2216 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2217 res = -1;
2218 else if (!opts->strategy ||
2219 !strcmp(opts->strategy, "recursive") ||
2220 !strcmp(opts->strategy, "ort") ||
2221 command == TODO_REVERT) {
2222 res = do_recursive_merge(r, base, next, base_label, next_label,
2223 &head, &msgbuf, opts);
2224 if (res < 0)
2225 goto leave;
2227 res |= write_message(msgbuf.buf, msgbuf.len,
2228 git_path_merge_msg(r), 0);
2229 } else {
2230 struct commit_list *common = NULL;
2231 struct commit_list *remotes = NULL;
2233 res = write_message(msgbuf.buf, msgbuf.len,
2234 git_path_merge_msg(r), 0);
2236 commit_list_insert(base, &common);
2237 commit_list_insert(next, &remotes);
2238 res |= try_merge_command(r, opts->strategy,
2239 opts->xopts_nr, (const char **)opts->xopts,
2240 common, oid_to_hex(&head), remotes);
2241 free_commit_list(common);
2242 free_commit_list(remotes);
2244 strbuf_release(&msgbuf);
2247 * If the merge was clean or if it failed due to conflict, we write
2248 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2249 * However, if the merge did not even start, then we don't want to
2250 * write it at all.
2252 if ((command == TODO_PICK || command == TODO_REWORD ||
2253 command == TODO_EDIT) && !opts->no_commit &&
2254 (res == 0 || res == 1) &&
2255 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2256 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2257 res = -1;
2258 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2259 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2260 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2261 res = -1;
2263 if (res) {
2264 error(command == TODO_REVERT
2265 ? _("could not revert %s... %s")
2266 : _("could not apply %s... %s"),
2267 short_commit_name(commit), msg.subject);
2268 print_advice(r, res == 1, opts);
2269 repo_rerere(r, opts->allow_rerere_auto);
2270 goto leave;
2273 drop_commit = 0;
2274 allow = allow_empty(r, opts, commit);
2275 if (allow < 0) {
2276 res = allow;
2277 goto leave;
2278 } else if (allow == 1) {
2279 flags |= ALLOW_EMPTY;
2280 } else if (allow == 2) {
2281 drop_commit = 1;
2282 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2283 NULL, 0);
2284 unlink(git_path_merge_msg(r));
2285 unlink(git_path_auto_merge(r));
2286 fprintf(stderr,
2287 _("dropping %s %s -- patch contents already upstream\n"),
2288 oid_to_hex(&commit->object.oid), msg.subject);
2289 } /* else allow == 0 and there's nothing special to do */
2290 if (!opts->no_commit && !drop_commit) {
2291 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2292 res = do_commit(r, msg_file, author, opts, flags,
2293 commit? &commit->object.oid : NULL);
2294 else
2295 res = error(_("unable to parse commit author"));
2296 *check_todo = !!(flags & EDIT_MSG);
2297 if (!res && reword) {
2298 fast_forward_edit:
2299 res = run_git_commit(NULL, opts, EDIT_MSG |
2300 VERIFY_MSG | AMEND_MSG |
2301 (flags & ALLOW_EMPTY));
2302 *check_todo = 1;
2307 if (!res && final_fixup) {
2308 unlink(rebase_path_fixup_msg());
2309 unlink(rebase_path_squash_msg());
2310 unlink(rebase_path_current_fixups());
2311 strbuf_reset(&opts->current_fixups);
2312 opts->current_fixup_count = 0;
2315 leave:
2316 free_message(commit, &msg);
2317 free(author);
2318 update_abort_safety_file();
2320 return res;
2323 static int prepare_revs(struct replay_opts *opts)
2326 * picking (but not reverting) ranges (but not individual revisions)
2327 * should be done in reverse
2329 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2330 opts->revs->reverse ^= 1;
2332 if (prepare_revision_walk(opts->revs))
2333 return error(_("revision walk setup failed"));
2335 return 0;
2338 static int read_and_refresh_cache(struct repository *r,
2339 struct replay_opts *opts)
2341 struct lock_file index_lock = LOCK_INIT;
2342 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2343 if (repo_read_index(r) < 0) {
2344 rollback_lock_file(&index_lock);
2345 return error(_("git %s: failed to read the index"),
2346 _(action_name(opts)));
2348 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2349 if (index_fd >= 0) {
2350 if (write_locked_index(r->index, &index_lock,
2351 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2352 return error(_("git %s: failed to refresh the index"),
2353 _(action_name(opts)));
2356 return 0;
2359 void todo_list_release(struct todo_list *todo_list)
2361 strbuf_release(&todo_list->buf);
2362 FREE_AND_NULL(todo_list->items);
2363 todo_list->nr = todo_list->alloc = 0;
2366 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2368 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2369 todo_list->total_nr++;
2370 return todo_list->items + todo_list->nr++;
2373 const char *todo_item_get_arg(struct todo_list *todo_list,
2374 struct todo_item *item)
2376 return todo_list->buf.buf + item->arg_offset;
2379 static int is_command(enum todo_command command, const char **bol)
2381 const char *str = todo_command_info[command].str;
2382 const char nick = todo_command_info[command].c;
2383 const char *p = *bol + 1;
2385 return skip_prefix(*bol, str, bol) ||
2386 ((nick && **bol == nick) &&
2387 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2388 (*bol = p));
2391 static int parse_insn_line(struct repository *r, struct todo_item *item,
2392 const char *buf, const char *bol, char *eol)
2394 struct object_id commit_oid;
2395 char *end_of_object_name;
2396 int i, saved, status, padding;
2398 item->flags = 0;
2400 /* left-trim */
2401 bol += strspn(bol, " \t");
2403 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2404 item->command = TODO_COMMENT;
2405 item->commit = NULL;
2406 item->arg_offset = bol - buf;
2407 item->arg_len = eol - bol;
2408 return 0;
2411 for (i = 0; i < TODO_COMMENT; i++)
2412 if (is_command(i, &bol)) {
2413 item->command = i;
2414 break;
2416 if (i >= TODO_COMMENT)
2417 return -1;
2419 /* Eat up extra spaces/ tabs before object name */
2420 padding = strspn(bol, " \t");
2421 bol += padding;
2423 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2424 if (bol != eol)
2425 return error(_("%s does not accept arguments: '%s'"),
2426 command_to_string(item->command), bol);
2427 item->commit = NULL;
2428 item->arg_offset = bol - buf;
2429 item->arg_len = eol - bol;
2430 return 0;
2433 if (!padding)
2434 return error(_("missing arguments for %s"),
2435 command_to_string(item->command));
2437 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2438 item->command == TODO_RESET) {
2439 item->commit = NULL;
2440 item->arg_offset = bol - buf;
2441 item->arg_len = (int)(eol - bol);
2442 return 0;
2445 if (item->command == TODO_FIXUP) {
2446 if (skip_prefix(bol, "-C", &bol) &&
2447 (*bol == ' ' || *bol == '\t')) {
2448 bol += strspn(bol, " \t");
2449 item->flags |= TODO_REPLACE_FIXUP_MSG;
2450 } else if (skip_prefix(bol, "-c", &bol) &&
2451 (*bol == ' ' || *bol == '\t')) {
2452 bol += strspn(bol, " \t");
2453 item->flags |= TODO_EDIT_FIXUP_MSG;
2457 if (item->command == TODO_MERGE) {
2458 if (skip_prefix(bol, "-C", &bol))
2459 bol += strspn(bol, " \t");
2460 else if (skip_prefix(bol, "-c", &bol)) {
2461 bol += strspn(bol, " \t");
2462 item->flags |= TODO_EDIT_MERGE_MSG;
2463 } else {
2464 item->flags |= TODO_EDIT_MERGE_MSG;
2465 item->commit = NULL;
2466 item->arg_offset = bol - buf;
2467 item->arg_len = (int)(eol - bol);
2468 return 0;
2472 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2473 saved = *end_of_object_name;
2474 *end_of_object_name = '\0';
2475 status = get_oid(bol, &commit_oid);
2476 if (status < 0)
2477 error(_("could not parse '%s'"), bol); /* return later */
2478 *end_of_object_name = saved;
2480 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2481 item->arg_offset = bol - buf;
2482 item->arg_len = (int)(eol - bol);
2484 if (status < 0)
2485 return status;
2487 item->commit = lookup_commit_reference(r, &commit_oid);
2488 return item->commit ? 0 : -1;
2491 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2493 const char *todo_file, *bol;
2494 struct strbuf buf = STRBUF_INIT;
2495 int ret = 0;
2497 todo_file = git_path_todo_file();
2498 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2499 if (errno == ENOENT || errno == ENOTDIR)
2500 return -1;
2501 else
2502 return error_errno("unable to open '%s'", todo_file);
2504 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2505 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2506 *action = REPLAY_PICK;
2507 else if (is_command(TODO_REVERT, &bol) &&
2508 (*bol == ' ' || *bol == '\t'))
2509 *action = REPLAY_REVERT;
2510 else
2511 ret = -1;
2513 strbuf_release(&buf);
2515 return ret;
2518 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2519 struct todo_list *todo_list)
2521 struct todo_item *item;
2522 char *p = buf, *next_p;
2523 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2525 todo_list->current = todo_list->nr = 0;
2527 for (i = 1; *p; i++, p = next_p) {
2528 char *eol = strchrnul(p, '\n');
2530 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2532 if (p != eol && eol[-1] == '\r')
2533 eol--; /* strip Carriage Return */
2535 item = append_new_todo(todo_list);
2536 item->offset_in_buf = p - todo_list->buf.buf;
2537 if (parse_insn_line(r, item, buf, p, eol)) {
2538 res = error(_("invalid line %d: %.*s"),
2539 i, (int)(eol - p), p);
2540 item->command = TODO_COMMENT + 1;
2541 item->arg_offset = p - buf;
2542 item->arg_len = (int)(eol - p);
2543 item->commit = NULL;
2546 if (fixup_okay)
2547 ; /* do nothing */
2548 else if (is_fixup(item->command))
2549 return error(_("cannot '%s' without a previous commit"),
2550 command_to_string(item->command));
2551 else if (!is_noop(item->command))
2552 fixup_okay = 1;
2555 return res;
2558 static int count_commands(struct todo_list *todo_list)
2560 int count = 0, i;
2562 for (i = 0; i < todo_list->nr; i++)
2563 if (todo_list->items[i].command != TODO_COMMENT)
2564 count++;
2566 return count;
2569 static int get_item_line_offset(struct todo_list *todo_list, int index)
2571 return index < todo_list->nr ?
2572 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2575 static const char *get_item_line(struct todo_list *todo_list, int index)
2577 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2580 static int get_item_line_length(struct todo_list *todo_list, int index)
2582 return get_item_line_offset(todo_list, index + 1)
2583 - get_item_line_offset(todo_list, index);
2586 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2588 int fd;
2589 ssize_t len;
2591 fd = open(path, O_RDONLY);
2592 if (fd < 0)
2593 return error_errno(_("could not open '%s'"), path);
2594 len = strbuf_read(sb, fd, 0);
2595 close(fd);
2596 if (len < 0)
2597 return error(_("could not read '%s'."), path);
2598 return len;
2601 static int have_finished_the_last_pick(void)
2603 struct strbuf buf = STRBUF_INIT;
2604 const char *eol;
2605 const char *todo_path = git_path_todo_file();
2606 int ret = 0;
2608 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2609 if (errno == ENOENT) {
2610 return 0;
2611 } else {
2612 error_errno("unable to open '%s'", todo_path);
2613 return 0;
2616 /* If there is only one line then we are done */
2617 eol = strchr(buf.buf, '\n');
2618 if (!eol || !eol[1])
2619 ret = 1;
2621 strbuf_release(&buf);
2623 return ret;
2626 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2628 struct replay_opts opts = REPLAY_OPTS_INIT;
2629 int need_cleanup = 0;
2631 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2632 if (!refs_delete_ref(get_main_ref_store(r), "",
2633 "CHERRY_PICK_HEAD", NULL, 0) &&
2634 verbose)
2635 warning(_("cancelling a cherry picking in progress"));
2636 opts.action = REPLAY_PICK;
2637 need_cleanup = 1;
2640 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2641 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2642 NULL, 0) &&
2643 verbose)
2644 warning(_("cancelling a revert in progress"));
2645 opts.action = REPLAY_REVERT;
2646 need_cleanup = 1;
2649 unlink(git_path_auto_merge(r));
2651 if (!need_cleanup)
2652 return;
2654 if (!have_finished_the_last_pick())
2655 return;
2657 sequencer_remove_state(&opts);
2660 static void todo_list_write_total_nr(struct todo_list *todo_list)
2662 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2664 if (f) {
2665 fprintf(f, "%d\n", todo_list->total_nr);
2666 fclose(f);
2670 static int read_populate_todo(struct repository *r,
2671 struct todo_list *todo_list,
2672 struct replay_opts *opts)
2674 struct stat st;
2675 const char *todo_file = get_todo_path(opts);
2676 int res;
2678 strbuf_reset(&todo_list->buf);
2679 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2680 return -1;
2682 res = stat(todo_file, &st);
2683 if (res)
2684 return error(_("could not stat '%s'"), todo_file);
2685 fill_stat_data(&todo_list->stat, &st);
2687 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2688 if (res) {
2689 if (is_rebase_i(opts))
2690 return error(_("please fix this using "
2691 "'git rebase --edit-todo'."));
2692 return error(_("unusable instruction sheet: '%s'"), todo_file);
2695 if (!todo_list->nr &&
2696 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2697 return error(_("no commits parsed."));
2699 if (!is_rebase_i(opts)) {
2700 enum todo_command valid =
2701 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2702 int i;
2704 for (i = 0; i < todo_list->nr; i++)
2705 if (valid == todo_list->items[i].command)
2706 continue;
2707 else if (valid == TODO_PICK)
2708 return error(_("cannot cherry-pick during a revert."));
2709 else
2710 return error(_("cannot revert during a cherry-pick."));
2713 if (is_rebase_i(opts)) {
2714 struct todo_list done = TODO_LIST_INIT;
2716 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2717 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2718 todo_list->done_nr = count_commands(&done);
2719 else
2720 todo_list->done_nr = 0;
2722 todo_list->total_nr = todo_list->done_nr
2723 + count_commands(todo_list);
2724 todo_list_release(&done);
2726 todo_list_write_total_nr(todo_list);
2729 return 0;
2732 static int git_config_string_dup(char **dest,
2733 const char *var, const char *value)
2735 if (!value)
2736 return config_error_nonbool(var);
2737 free(*dest);
2738 *dest = xstrdup(value);
2739 return 0;
2742 static int populate_opts_cb(const char *key, const char *value, void *data)
2744 struct replay_opts *opts = data;
2745 int error_flag = 1;
2747 if (!value)
2748 error_flag = 0;
2749 else if (!strcmp(key, "options.no-commit"))
2750 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2751 else if (!strcmp(key, "options.edit"))
2752 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2753 else if (!strcmp(key, "options.allow-empty"))
2754 opts->allow_empty =
2755 git_config_bool_or_int(key, value, &error_flag);
2756 else if (!strcmp(key, "options.allow-empty-message"))
2757 opts->allow_empty_message =
2758 git_config_bool_or_int(key, value, &error_flag);
2759 else if (!strcmp(key, "options.keep-redundant-commits"))
2760 opts->keep_redundant_commits =
2761 git_config_bool_or_int(key, value, &error_flag);
2762 else if (!strcmp(key, "options.signoff"))
2763 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2764 else if (!strcmp(key, "options.record-origin"))
2765 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2766 else if (!strcmp(key, "options.allow-ff"))
2767 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2768 else if (!strcmp(key, "options.mainline"))
2769 opts->mainline = git_config_int(key, value);
2770 else if (!strcmp(key, "options.strategy"))
2771 git_config_string_dup(&opts->strategy, key, value);
2772 else if (!strcmp(key, "options.gpg-sign"))
2773 git_config_string_dup(&opts->gpg_sign, key, value);
2774 else if (!strcmp(key, "options.strategy-option")) {
2775 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2776 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2777 } else if (!strcmp(key, "options.allow-rerere-auto"))
2778 opts->allow_rerere_auto =
2779 git_config_bool_or_int(key, value, &error_flag) ?
2780 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2781 else if (!strcmp(key, "options.default-msg-cleanup")) {
2782 opts->explicit_cleanup = 1;
2783 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2784 } else
2785 return error(_("invalid key: %s"), key);
2787 if (!error_flag)
2788 return error(_("invalid value for %s: %s"), key, value);
2790 return 0;
2793 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2795 int i;
2796 char *strategy_opts_string = raw_opts;
2798 if (*strategy_opts_string == ' ')
2799 strategy_opts_string++;
2801 opts->xopts_nr = split_cmdline(strategy_opts_string,
2802 (const char ***)&opts->xopts);
2803 for (i = 0; i < opts->xopts_nr; i++) {
2804 const char *arg = opts->xopts[i];
2806 skip_prefix(arg, "--", &arg);
2807 opts->xopts[i] = xstrdup(arg);
2811 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2813 strbuf_reset(buf);
2814 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2815 return;
2816 opts->strategy = strbuf_detach(buf, NULL);
2817 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2818 return;
2820 parse_strategy_opts(opts, buf->buf);
2823 static int read_populate_opts(struct replay_opts *opts)
2825 if (is_rebase_i(opts)) {
2826 struct strbuf buf = STRBUF_INIT;
2827 int ret = 0;
2829 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2830 READ_ONELINER_SKIP_IF_EMPTY)) {
2831 if (!starts_with(buf.buf, "-S"))
2832 strbuf_reset(&buf);
2833 else {
2834 free(opts->gpg_sign);
2835 opts->gpg_sign = xstrdup(buf.buf + 2);
2837 strbuf_reset(&buf);
2840 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2841 READ_ONELINER_SKIP_IF_EMPTY)) {
2842 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2843 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2844 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2845 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2846 strbuf_reset(&buf);
2849 if (file_exists(rebase_path_verbose()))
2850 opts->verbose = 1;
2852 if (file_exists(rebase_path_quiet()))
2853 opts->quiet = 1;
2855 if (file_exists(rebase_path_signoff())) {
2856 opts->allow_ff = 0;
2857 opts->signoff = 1;
2860 if (file_exists(rebase_path_cdate_is_adate())) {
2861 opts->allow_ff = 0;
2862 opts->committer_date_is_author_date = 1;
2865 if (file_exists(rebase_path_ignore_date())) {
2866 opts->allow_ff = 0;
2867 opts->ignore_date = 1;
2870 if (file_exists(rebase_path_reschedule_failed_exec()))
2871 opts->reschedule_failed_exec = 1;
2872 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2873 opts->reschedule_failed_exec = 0;
2875 if (file_exists(rebase_path_drop_redundant_commits()))
2876 opts->drop_redundant_commits = 1;
2878 if (file_exists(rebase_path_keep_redundant_commits()))
2879 opts->keep_redundant_commits = 1;
2881 read_strategy_opts(opts, &buf);
2882 strbuf_reset(&buf);
2884 if (read_oneliner(&opts->current_fixups,
2885 rebase_path_current_fixups(),
2886 READ_ONELINER_SKIP_IF_EMPTY)) {
2887 const char *p = opts->current_fixups.buf;
2888 opts->current_fixup_count = 1;
2889 while ((p = strchr(p, '\n'))) {
2890 opts->current_fixup_count++;
2891 p++;
2895 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2896 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2897 ret = error(_("unusable squash-onto"));
2898 goto done_rebase_i;
2900 opts->have_squash_onto = 1;
2903 done_rebase_i:
2904 strbuf_release(&buf);
2905 return ret;
2908 if (!file_exists(git_path_opts_file()))
2909 return 0;
2911 * The function git_parse_source(), called from git_config_from_file(),
2912 * may die() in case of a syntactically incorrect file. We do not care
2913 * about this case, though, because we wrote that file ourselves, so we
2914 * are pretty certain that it is syntactically correct.
2916 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2917 return error(_("malformed options sheet: '%s'"),
2918 git_path_opts_file());
2919 return 0;
2922 static void write_strategy_opts(struct replay_opts *opts)
2924 int i;
2925 struct strbuf buf = STRBUF_INIT;
2927 for (i = 0; i < opts->xopts_nr; ++i)
2928 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2930 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2931 strbuf_release(&buf);
2934 int write_basic_state(struct replay_opts *opts, const char *head_name,
2935 struct commit *onto, const struct object_id *orig_head)
2937 if (head_name)
2938 write_file(rebase_path_head_name(), "%s\n", head_name);
2939 if (onto)
2940 write_file(rebase_path_onto(), "%s\n",
2941 oid_to_hex(&onto->object.oid));
2942 if (orig_head)
2943 write_file(rebase_path_orig_head(), "%s\n",
2944 oid_to_hex(orig_head));
2946 if (opts->quiet)
2947 write_file(rebase_path_quiet(), "%s", "");
2948 if (opts->verbose)
2949 write_file(rebase_path_verbose(), "%s", "");
2950 if (opts->strategy)
2951 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2952 if (opts->xopts_nr > 0)
2953 write_strategy_opts(opts);
2955 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2956 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2957 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2958 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2960 if (opts->gpg_sign)
2961 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2962 if (opts->signoff)
2963 write_file(rebase_path_signoff(), "--signoff\n");
2964 if (opts->drop_redundant_commits)
2965 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2966 if (opts->keep_redundant_commits)
2967 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2968 if (opts->committer_date_is_author_date)
2969 write_file(rebase_path_cdate_is_adate(), "%s", "");
2970 if (opts->ignore_date)
2971 write_file(rebase_path_ignore_date(), "%s", "");
2972 if (opts->reschedule_failed_exec)
2973 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2974 else
2975 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2977 return 0;
2980 static int walk_revs_populate_todo(struct todo_list *todo_list,
2981 struct replay_opts *opts)
2983 enum todo_command command = opts->action == REPLAY_PICK ?
2984 TODO_PICK : TODO_REVERT;
2985 const char *command_string = todo_command_info[command].str;
2986 const char *encoding;
2987 struct commit *commit;
2989 if (prepare_revs(opts))
2990 return -1;
2992 encoding = get_log_output_encoding();
2994 while ((commit = get_revision(opts->revs))) {
2995 struct todo_item *item = append_new_todo(todo_list);
2996 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2997 const char *subject;
2998 int subject_len;
3000 item->command = command;
3001 item->commit = commit;
3002 item->arg_offset = 0;
3003 item->arg_len = 0;
3004 item->offset_in_buf = todo_list->buf.len;
3005 subject_len = find_commit_subject(commit_buffer, &subject);
3006 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3007 short_commit_name(commit), subject_len, subject);
3008 unuse_commit_buffer(commit, commit_buffer);
3011 if (!todo_list->nr)
3012 return error(_("empty commit set passed"));
3014 return 0;
3017 static int create_seq_dir(struct repository *r)
3019 enum replay_action action;
3020 const char *in_progress_error = NULL;
3021 const char *in_progress_advice = NULL;
3022 unsigned int advise_skip =
3023 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3024 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3026 if (!sequencer_get_last_command(r, &action)) {
3027 switch (action) {
3028 case REPLAY_REVERT:
3029 in_progress_error = _("revert is already in progress");
3030 in_progress_advice =
3031 _("try \"git revert (--continue | %s--abort | --quit)\"");
3032 break;
3033 case REPLAY_PICK:
3034 in_progress_error = _("cherry-pick is already in progress");
3035 in_progress_advice =
3036 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3037 break;
3038 default:
3039 BUG("unexpected action in create_seq_dir");
3042 if (in_progress_error) {
3043 error("%s", in_progress_error);
3044 if (advice_sequencer_in_use)
3045 advise(in_progress_advice,
3046 advise_skip ? "--skip | " : "");
3047 return -1;
3049 if (mkdir(git_path_seq_dir(), 0777) < 0)
3050 return error_errno(_("could not create sequencer directory '%s'"),
3051 git_path_seq_dir());
3053 return 0;
3056 static int save_head(const char *head)
3058 struct lock_file head_lock = LOCK_INIT;
3059 struct strbuf buf = STRBUF_INIT;
3060 int fd;
3061 ssize_t written;
3063 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3064 if (fd < 0)
3065 return error_errno(_("could not lock HEAD"));
3066 strbuf_addf(&buf, "%s\n", head);
3067 written = write_in_full(fd, buf.buf, buf.len);
3068 strbuf_release(&buf);
3069 if (written < 0) {
3070 error_errno(_("could not write to '%s'"), git_path_head_file());
3071 rollback_lock_file(&head_lock);
3072 return -1;
3074 if (commit_lock_file(&head_lock) < 0)
3075 return error(_("failed to finalize '%s'"), git_path_head_file());
3076 return 0;
3079 static int rollback_is_safe(void)
3081 struct strbuf sb = STRBUF_INIT;
3082 struct object_id expected_head, actual_head;
3084 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3085 strbuf_trim(&sb);
3086 if (get_oid_hex(sb.buf, &expected_head)) {
3087 strbuf_release(&sb);
3088 die(_("could not parse %s"), git_path_abort_safety_file());
3090 strbuf_release(&sb);
3092 else if (errno == ENOENT)
3093 oidclr(&expected_head);
3094 else
3095 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3097 if (get_oid("HEAD", &actual_head))
3098 oidclr(&actual_head);
3100 return oideq(&actual_head, &expected_head);
3103 static int reset_merge(const struct object_id *oid)
3105 int ret;
3106 struct strvec argv = STRVEC_INIT;
3108 strvec_pushl(&argv, "reset", "--merge", NULL);
3110 if (!is_null_oid(oid))
3111 strvec_push(&argv, oid_to_hex(oid));
3113 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3114 strvec_clear(&argv);
3116 return ret;
3119 static int rollback_single_pick(struct repository *r)
3121 struct object_id head_oid;
3123 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3124 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3125 return error(_("no cherry-pick or revert in progress"));
3126 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3127 return error(_("cannot resolve HEAD"));
3128 if (is_null_oid(&head_oid))
3129 return error(_("cannot abort from a branch yet to be born"));
3130 return reset_merge(&head_oid);
3133 static int skip_single_pick(void)
3135 struct object_id head;
3137 if (read_ref_full("HEAD", 0, &head, NULL))
3138 return error(_("cannot resolve HEAD"));
3139 return reset_merge(&head);
3142 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3144 FILE *f;
3145 struct object_id oid;
3146 struct strbuf buf = STRBUF_INIT;
3147 const char *p;
3149 f = fopen(git_path_head_file(), "r");
3150 if (!f && errno == ENOENT) {
3152 * There is no multiple-cherry-pick in progress.
3153 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3154 * a single-cherry-pick in progress, abort that.
3156 return rollback_single_pick(r);
3158 if (!f)
3159 return error_errno(_("cannot open '%s'"), git_path_head_file());
3160 if (strbuf_getline_lf(&buf, f)) {
3161 error(_("cannot read '%s': %s"), git_path_head_file(),
3162 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3163 fclose(f);
3164 goto fail;
3166 fclose(f);
3167 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3168 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3169 git_path_head_file());
3170 goto fail;
3172 if (is_null_oid(&oid)) {
3173 error(_("cannot abort from a branch yet to be born"));
3174 goto fail;
3177 if (!rollback_is_safe()) {
3178 /* Do not error, just do not rollback */
3179 warning(_("You seem to have moved HEAD. "
3180 "Not rewinding, check your HEAD!"));
3181 } else
3182 if (reset_merge(&oid))
3183 goto fail;
3184 strbuf_release(&buf);
3185 return sequencer_remove_state(opts);
3186 fail:
3187 strbuf_release(&buf);
3188 return -1;
3191 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3193 enum replay_action action = -1;
3194 sequencer_get_last_command(r, &action);
3197 * Check whether the subcommand requested to skip the commit is actually
3198 * in progress and that it's safe to skip the commit.
3200 * opts->action tells us which subcommand requested to skip the commit.
3201 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3202 * action is in progress and we can skip the commit.
3204 * Otherwise we check that the last instruction was related to the
3205 * particular subcommand we're trying to execute and barf if that's not
3206 * the case.
3208 * Finally we check that the rollback is "safe", i.e., has the HEAD
3209 * moved? In this case, it doesn't make sense to "reset the merge" and
3210 * "skip the commit" as the user already handled this by committing. But
3211 * we'd not want to barf here, instead give advice on how to proceed. We
3212 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3213 * it gets removed when the user commits, so if it still exists we're
3214 * sure the user can't have committed before.
3216 switch (opts->action) {
3217 case REPLAY_REVERT:
3218 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3219 if (action != REPLAY_REVERT)
3220 return error(_("no revert in progress"));
3221 if (!rollback_is_safe())
3222 goto give_advice;
3224 break;
3225 case REPLAY_PICK:
3226 if (!refs_ref_exists(get_main_ref_store(r),
3227 "CHERRY_PICK_HEAD")) {
3228 if (action != REPLAY_PICK)
3229 return error(_("no cherry-pick in progress"));
3230 if (!rollback_is_safe())
3231 goto give_advice;
3233 break;
3234 default:
3235 BUG("unexpected action in sequencer_skip");
3238 if (skip_single_pick())
3239 return error(_("failed to skip the commit"));
3240 if (!is_directory(git_path_seq_dir()))
3241 return 0;
3243 return sequencer_continue(r, opts);
3245 give_advice:
3246 error(_("there is nothing to skip"));
3248 if (advice_resolve_conflict) {
3249 advise(_("have you committed already?\n"
3250 "try \"git %s --continue\""),
3251 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3253 return -1;
3256 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3258 struct lock_file todo_lock = LOCK_INIT;
3259 const char *todo_path = get_todo_path(opts);
3260 int next = todo_list->current, offset, fd;
3263 * rebase -i writes "git-rebase-todo" without the currently executing
3264 * command, appending it to "done" instead.
3266 if (is_rebase_i(opts))
3267 next++;
3269 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3270 if (fd < 0)
3271 return error_errno(_("could not lock '%s'"), todo_path);
3272 offset = get_item_line_offset(todo_list, next);
3273 if (write_in_full(fd, todo_list->buf.buf + offset,
3274 todo_list->buf.len - offset) < 0)
3275 return error_errno(_("could not write to '%s'"), todo_path);
3276 if (commit_lock_file(&todo_lock) < 0)
3277 return error(_("failed to finalize '%s'"), todo_path);
3279 if (is_rebase_i(opts) && next > 0) {
3280 const char *done = rebase_path_done();
3281 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3282 int ret = 0;
3284 if (fd < 0)
3285 return 0;
3286 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3287 get_item_line_length(todo_list, next - 1))
3288 < 0)
3289 ret = error_errno(_("could not write to '%s'"), done);
3290 if (close(fd) < 0)
3291 ret = error_errno(_("failed to finalize '%s'"), done);
3292 return ret;
3294 return 0;
3297 static int save_opts(struct replay_opts *opts)
3299 const char *opts_file = git_path_opts_file();
3300 int res = 0;
3302 if (opts->no_commit)
3303 res |= git_config_set_in_file_gently(opts_file,
3304 "options.no-commit", "true");
3305 if (opts->edit >= 0)
3306 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3307 opts->edit ? "true" : "false");
3308 if (opts->allow_empty)
3309 res |= git_config_set_in_file_gently(opts_file,
3310 "options.allow-empty", "true");
3311 if (opts->allow_empty_message)
3312 res |= git_config_set_in_file_gently(opts_file,
3313 "options.allow-empty-message", "true");
3314 if (opts->keep_redundant_commits)
3315 res |= git_config_set_in_file_gently(opts_file,
3316 "options.keep-redundant-commits", "true");
3317 if (opts->signoff)
3318 res |= git_config_set_in_file_gently(opts_file,
3319 "options.signoff", "true");
3320 if (opts->record_origin)
3321 res |= git_config_set_in_file_gently(opts_file,
3322 "options.record-origin", "true");
3323 if (opts->allow_ff)
3324 res |= git_config_set_in_file_gently(opts_file,
3325 "options.allow-ff", "true");
3326 if (opts->mainline) {
3327 struct strbuf buf = STRBUF_INIT;
3328 strbuf_addf(&buf, "%d", opts->mainline);
3329 res |= git_config_set_in_file_gently(opts_file,
3330 "options.mainline", buf.buf);
3331 strbuf_release(&buf);
3333 if (opts->strategy)
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.strategy", opts->strategy);
3336 if (opts->gpg_sign)
3337 res |= git_config_set_in_file_gently(opts_file,
3338 "options.gpg-sign", opts->gpg_sign);
3339 if (opts->xopts) {
3340 int i;
3341 for (i = 0; i < opts->xopts_nr; i++)
3342 res |= git_config_set_multivar_in_file_gently(opts_file,
3343 "options.strategy-option",
3344 opts->xopts[i], "^$", 0);
3346 if (opts->allow_rerere_auto)
3347 res |= git_config_set_in_file_gently(opts_file,
3348 "options.allow-rerere-auto",
3349 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3350 "true" : "false");
3352 if (opts->explicit_cleanup)
3353 res |= git_config_set_in_file_gently(opts_file,
3354 "options.default-msg-cleanup",
3355 describe_cleanup_mode(opts->default_msg_cleanup));
3356 return res;
3359 static int make_patch(struct repository *r,
3360 struct commit *commit,
3361 struct replay_opts *opts)
3363 struct strbuf buf = STRBUF_INIT;
3364 struct rev_info log_tree_opt;
3365 const char *subject;
3366 char hex[GIT_MAX_HEXSZ + 1];
3367 int res = 0;
3369 oid_to_hex_r(hex, &commit->object.oid);
3370 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3371 return -1;
3372 res |= write_rebase_head(&commit->object.oid);
3374 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3375 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3376 repo_init_revisions(r, &log_tree_opt, NULL);
3377 log_tree_opt.abbrev = 0;
3378 log_tree_opt.diff = 1;
3379 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3380 log_tree_opt.disable_stdin = 1;
3381 log_tree_opt.no_commit_id = 1;
3382 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3383 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3384 if (!log_tree_opt.diffopt.file)
3385 res |= error_errno(_("could not open '%s'"), buf.buf);
3386 else {
3387 res |= log_tree_commit(&log_tree_opt, commit);
3388 fclose(log_tree_opt.diffopt.file);
3390 strbuf_reset(&buf);
3392 strbuf_addf(&buf, "%s/message", get_dir(opts));
3393 if (!file_exists(buf.buf)) {
3394 const char *encoding = get_commit_output_encoding();
3395 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3396 find_commit_subject(commit_buffer, &subject);
3397 res |= write_message(subject, strlen(subject), buf.buf, 1);
3398 unuse_commit_buffer(commit, commit_buffer);
3400 strbuf_release(&buf);
3402 return res;
3405 static int intend_to_amend(void)
3407 struct object_id head;
3408 char *p;
3410 if (get_oid("HEAD", &head))
3411 return error(_("cannot read HEAD"));
3413 p = oid_to_hex(&head);
3414 return write_message(p, strlen(p), rebase_path_amend(), 1);
3417 static int error_with_patch(struct repository *r,
3418 struct commit *commit,
3419 const char *subject, int subject_len,
3420 struct replay_opts *opts,
3421 int exit_code, int to_amend)
3423 if (commit) {
3424 if (make_patch(r, commit, opts))
3425 return -1;
3426 } else if (copy_file(rebase_path_message(),
3427 git_path_merge_msg(r), 0666))
3428 return error(_("unable to copy '%s' to '%s'"),
3429 git_path_merge_msg(r), rebase_path_message());
3431 if (to_amend) {
3432 if (intend_to_amend())
3433 return -1;
3435 fprintf(stderr,
3436 _("You can amend the commit now, with\n"
3437 "\n"
3438 " git commit --amend %s\n"
3439 "\n"
3440 "Once you are satisfied with your changes, run\n"
3441 "\n"
3442 " git rebase --continue\n"),
3443 gpg_sign_opt_quoted(opts));
3444 } else if (exit_code) {
3445 if (commit)
3446 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3447 short_commit_name(commit), subject_len, subject);
3448 else
3450 * We don't have the hash of the parent so
3451 * just print the line from the todo file.
3453 fprintf_ln(stderr, _("Could not merge %.*s"),
3454 subject_len, subject);
3457 return exit_code;
3460 static int error_failed_squash(struct repository *r,
3461 struct commit *commit,
3462 struct replay_opts *opts,
3463 int subject_len,
3464 const char *subject)
3466 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3467 return error(_("could not copy '%s' to '%s'"),
3468 rebase_path_squash_msg(), rebase_path_message());
3469 unlink(git_path_merge_msg(r));
3470 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3471 return error(_("could not copy '%s' to '%s'"),
3472 rebase_path_message(),
3473 git_path_merge_msg(r));
3474 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3477 static int do_exec(struct repository *r, const char *command_line)
3479 struct strvec child_env = STRVEC_INIT;
3480 const char *child_argv[] = { NULL, NULL };
3481 int dirty, status;
3483 fprintf(stderr, _("Executing: %s\n"), command_line);
3484 child_argv[0] = command_line;
3485 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3486 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3487 absolute_path(get_git_work_tree()));
3488 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3489 child_env.v);
3491 /* force re-reading of the cache */
3492 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3493 return error(_("could not read index"));
3495 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3497 if (status) {
3498 warning(_("execution failed: %s\n%s"
3499 "You can fix the problem, and then run\n"
3500 "\n"
3501 " git rebase --continue\n"
3502 "\n"),
3503 command_line,
3504 dirty ? N_("and made changes to the index and/or the "
3505 "working tree\n") : "");
3506 if (status == 127)
3507 /* command not found */
3508 status = 1;
3509 } else if (dirty) {
3510 warning(_("execution succeeded: %s\nbut "
3511 "left changes to the index and/or the working tree\n"
3512 "Commit or stash your changes, and then run\n"
3513 "\n"
3514 " git rebase --continue\n"
3515 "\n"), command_line);
3516 status = 1;
3519 strvec_clear(&child_env);
3521 return status;
3524 __attribute__((format (printf, 2, 3)))
3525 static int safe_append(const char *filename, const char *fmt, ...)
3527 va_list ap;
3528 struct lock_file lock = LOCK_INIT;
3529 int fd = hold_lock_file_for_update(&lock, filename,
3530 LOCK_REPORT_ON_ERROR);
3531 struct strbuf buf = STRBUF_INIT;
3533 if (fd < 0)
3534 return -1;
3536 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3537 error_errno(_("could not read '%s'"), filename);
3538 rollback_lock_file(&lock);
3539 return -1;
3541 strbuf_complete(&buf, '\n');
3542 va_start(ap, fmt);
3543 strbuf_vaddf(&buf, fmt, ap);
3544 va_end(ap);
3546 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3547 error_errno(_("could not write to '%s'"), filename);
3548 strbuf_release(&buf);
3549 rollback_lock_file(&lock);
3550 return -1;
3552 if (commit_lock_file(&lock) < 0) {
3553 strbuf_release(&buf);
3554 rollback_lock_file(&lock);
3555 return error(_("failed to finalize '%s'"), filename);
3558 strbuf_release(&buf);
3559 return 0;
3562 static int do_label(struct repository *r, const char *name, int len)
3564 struct ref_store *refs = get_main_ref_store(r);
3565 struct ref_transaction *transaction;
3566 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3567 struct strbuf msg = STRBUF_INIT;
3568 int ret = 0;
3569 struct object_id head_oid;
3571 if (len == 1 && *name == '#')
3572 return error(_("illegal label name: '%.*s'"), len, name);
3574 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3575 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3577 transaction = ref_store_transaction_begin(refs, &err);
3578 if (!transaction) {
3579 error("%s", err.buf);
3580 ret = -1;
3581 } else if (get_oid("HEAD", &head_oid)) {
3582 error(_("could not read HEAD"));
3583 ret = -1;
3584 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3585 NULL, 0, msg.buf, &err) < 0 ||
3586 ref_transaction_commit(transaction, &err)) {
3587 error("%s", err.buf);
3588 ret = -1;
3590 ref_transaction_free(transaction);
3591 strbuf_release(&err);
3592 strbuf_release(&msg);
3594 if (!ret)
3595 ret = safe_append(rebase_path_refs_to_delete(),
3596 "%s\n", ref_name.buf);
3597 strbuf_release(&ref_name);
3599 return ret;
3602 __attribute__((format (printf, 3, 4)))
3603 static const char *reflog_message(struct replay_opts *opts,
3604 const char *sub_action, const char *fmt, ...)
3606 va_list ap;
3607 static struct strbuf buf = STRBUF_INIT;
3608 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3610 va_start(ap, fmt);
3611 strbuf_reset(&buf);
3612 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3613 if (sub_action)
3614 strbuf_addf(&buf, " (%s)", sub_action);
3615 if (fmt) {
3616 strbuf_addstr(&buf, ": ");
3617 strbuf_vaddf(&buf, fmt, ap);
3619 va_end(ap);
3621 return buf.buf;
3624 static int do_reset(struct repository *r,
3625 const char *name, int len,
3626 struct replay_opts *opts)
3628 struct strbuf ref_name = STRBUF_INIT;
3629 struct object_id oid;
3630 struct lock_file lock = LOCK_INIT;
3631 struct tree_desc desc;
3632 struct tree *tree;
3633 struct unpack_trees_options unpack_tree_opts;
3634 int ret = 0;
3636 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3637 return -1;
3639 if (len == 10 && !strncmp("[new root]", name, len)) {
3640 if (!opts->have_squash_onto) {
3641 const char *hex;
3642 if (commit_tree("", 0, the_hash_algo->empty_tree,
3643 NULL, &opts->squash_onto,
3644 NULL, NULL))
3645 return error(_("writing fake root commit"));
3646 opts->have_squash_onto = 1;
3647 hex = oid_to_hex(&opts->squash_onto);
3648 if (write_message(hex, strlen(hex),
3649 rebase_path_squash_onto(), 0))
3650 return error(_("writing squash-onto"));
3652 oidcpy(&oid, &opts->squash_onto);
3653 } else {
3654 int i;
3656 /* Determine the length of the label */
3657 for (i = 0; i < len; i++)
3658 if (isspace(name[i]))
3659 break;
3660 len = i;
3662 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3663 if (get_oid(ref_name.buf, &oid) &&
3664 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3665 error(_("could not read '%s'"), ref_name.buf);
3666 rollback_lock_file(&lock);
3667 strbuf_release(&ref_name);
3668 return -1;
3672 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3673 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3674 unpack_tree_opts.head_idx = 1;
3675 unpack_tree_opts.src_index = r->index;
3676 unpack_tree_opts.dst_index = r->index;
3677 unpack_tree_opts.fn = oneway_merge;
3678 unpack_tree_opts.merge = 1;
3679 unpack_tree_opts.update = 1;
3680 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3682 if (repo_read_index_unmerged(r)) {
3683 rollback_lock_file(&lock);
3684 strbuf_release(&ref_name);
3685 return error_resolve_conflict(_(action_name(opts)));
3688 if (!fill_tree_descriptor(r, &desc, &oid)) {
3689 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3690 rollback_lock_file(&lock);
3691 free((void *)desc.buffer);
3692 strbuf_release(&ref_name);
3693 return -1;
3696 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3697 rollback_lock_file(&lock);
3698 free((void *)desc.buffer);
3699 strbuf_release(&ref_name);
3700 return -1;
3703 tree = parse_tree_indirect(&oid);
3704 prime_cache_tree(r, r->index, tree);
3706 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3707 ret = error(_("could not write index"));
3708 free((void *)desc.buffer);
3710 if (!ret)
3711 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3712 len, name), "HEAD", &oid,
3713 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3715 strbuf_release(&ref_name);
3716 return ret;
3719 static struct commit *lookup_label(const char *label, int len,
3720 struct strbuf *buf)
3722 struct commit *commit;
3724 strbuf_reset(buf);
3725 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3726 commit = lookup_commit_reference_by_name(buf->buf);
3727 if (!commit) {
3728 /* fall back to non-rewritten ref or commit */
3729 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3730 commit = lookup_commit_reference_by_name(buf->buf);
3733 if (!commit)
3734 error(_("could not resolve '%s'"), buf->buf);
3736 return commit;
3739 static int do_merge(struct repository *r,
3740 struct commit *commit,
3741 const char *arg, int arg_len,
3742 int flags, struct replay_opts *opts)
3744 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3745 EDIT_MSG | VERIFY_MSG : 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;
3819 if (commit) {
3820 const char *encoding = get_commit_output_encoding();
3821 const char *message = logmsg_reencode(commit, NULL, encoding);
3822 const char *body;
3823 int len;
3825 if (!message) {
3826 ret = error(_("could not get commit message of '%s'"),
3827 oid_to_hex(&commit->object.oid));
3828 goto leave_merge;
3830 write_author_script(message);
3831 find_commit_subject(message, &body);
3832 len = strlen(body);
3833 ret = write_message(body, len, git_path_merge_msg(r), 0);
3834 unuse_commit_buffer(commit, message);
3835 if (ret) {
3836 error_errno(_("could not write '%s'"),
3837 git_path_merge_msg(r));
3838 goto leave_merge;
3840 } else {
3841 struct strbuf buf = STRBUF_INIT;
3842 int len;
3844 strbuf_addf(&buf, "author %s", git_author_info(0));
3845 write_author_script(buf.buf);
3846 strbuf_reset(&buf);
3848 if (oneline_offset < arg_len) {
3849 p = arg + oneline_offset;
3850 len = arg_len - oneline_offset;
3851 } else {
3852 strbuf_addf(&buf, "Merge %s '%.*s'",
3853 to_merge->next ? "branches" : "branch",
3854 merge_arg_len, arg);
3855 p = buf.buf;
3856 len = buf.len;
3859 ret = write_message(p, len, git_path_merge_msg(r), 0);
3860 strbuf_release(&buf);
3861 if (ret) {
3862 error_errno(_("could not write '%s'"),
3863 git_path_merge_msg(r));
3864 goto leave_merge;
3869 * If HEAD is not identical to the first parent of the original merge
3870 * commit, we cannot fast-forward.
3872 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3873 oideq(&commit->parents->item->object.oid,
3874 &head_commit->object.oid);
3877 * If any merge head is different from the original one, we cannot
3878 * fast-forward.
3880 if (can_fast_forward) {
3881 struct commit_list *p = commit->parents->next;
3883 for (j = to_merge; j && p; j = j->next, p = p->next)
3884 if (!oideq(&j->item->object.oid,
3885 &p->item->object.oid)) {
3886 can_fast_forward = 0;
3887 break;
3890 * If the number of merge heads differs from the original merge
3891 * commit, we cannot fast-forward.
3893 if (j || p)
3894 can_fast_forward = 0;
3897 if (can_fast_forward) {
3898 rollback_lock_file(&lock);
3899 ret = fast_forward_to(r, &commit->object.oid,
3900 &head_commit->object.oid, 0, opts);
3901 if (flags & TODO_EDIT_MERGE_MSG) {
3902 run_commit_flags |= AMEND_MSG;
3903 goto fast_forward_edit;
3905 goto leave_merge;
3908 if (strategy || to_merge->next) {
3909 /* Octopus merge */
3910 struct child_process cmd = CHILD_PROCESS_INIT;
3912 if (read_env_script(&cmd.env_array)) {
3913 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3915 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3916 goto leave_merge;
3919 if (opts->committer_date_is_author_date)
3920 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3921 opts->ignore_date ?
3922 "" :
3923 author_date_from_env_array(&cmd.env_array));
3924 if (opts->ignore_date)
3925 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3927 cmd.git_cmd = 1;
3928 strvec_push(&cmd.args, "merge");
3929 strvec_push(&cmd.args, "-s");
3930 if (!strategy)
3931 strvec_push(&cmd.args, "octopus");
3932 else {
3933 strvec_push(&cmd.args, strategy);
3934 for (k = 0; k < opts->xopts_nr; k++)
3935 strvec_pushf(&cmd.args,
3936 "-X%s", opts->xopts[k]);
3938 strvec_push(&cmd.args, "--no-edit");
3939 strvec_push(&cmd.args, "--no-ff");
3940 strvec_push(&cmd.args, "--no-log");
3941 strvec_push(&cmd.args, "--no-stat");
3942 strvec_push(&cmd.args, "-F");
3943 strvec_push(&cmd.args, git_path_merge_msg(r));
3944 if (opts->gpg_sign)
3945 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3946 else
3947 strvec_push(&cmd.args, "--no-gpg-sign");
3949 /* Add the tips to be merged */
3950 for (j = to_merge; j; j = j->next)
3951 strvec_push(&cmd.args,
3952 oid_to_hex(&j->item->object.oid));
3954 strbuf_release(&ref_name);
3955 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3956 NULL, 0);
3957 rollback_lock_file(&lock);
3959 ret = run_command(&cmd);
3961 /* force re-reading of the cache */
3962 if (!ret && (discard_index(r->index) < 0 ||
3963 repo_read_index(r) < 0))
3964 ret = error(_("could not read index"));
3965 goto leave_merge;
3968 merge_commit = to_merge->item;
3969 bases = get_merge_bases(head_commit, merge_commit);
3970 if (bases && oideq(&merge_commit->object.oid,
3971 &bases->item->object.oid)) {
3972 ret = 0;
3973 /* skip merging an ancestor of HEAD */
3974 goto leave_merge;
3977 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3978 git_path_merge_head(r), 0);
3979 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3981 for (j = bases; j; j = j->next)
3982 commit_list_insert(j->item, &reversed);
3983 free_commit_list(bases);
3985 repo_read_index(r);
3986 init_merge_options(&o, r);
3987 o.branch1 = "HEAD";
3988 o.branch2 = ref_name.buf;
3989 o.buffer_output = 2;
3991 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3993 * TODO: Should use merge_incore_recursive() and
3994 * merge_switch_to_result(), skipping the call to
3995 * merge_switch_to_result() when we don't actually need to
3996 * update the index and working copy immediately.
3998 ret = merge_ort_recursive(&o,
3999 head_commit, merge_commit, reversed,
4000 &i);
4001 } else {
4002 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4003 &i);
4005 if (ret <= 0)
4006 fputs(o.obuf.buf, stdout);
4007 strbuf_release(&o.obuf);
4008 if (ret < 0) {
4009 error(_("could not even attempt to merge '%.*s'"),
4010 merge_arg_len, arg);
4011 goto leave_merge;
4014 * The return value of merge_recursive() is 1 on clean, and 0 on
4015 * unclean merge.
4017 * Let's reverse that, so that do_merge() returns 0 upon success and
4018 * 1 upon failed merge (keeping the return value -1 for the cases where
4019 * we will want to reschedule the `merge` command).
4021 ret = !ret;
4023 if (r->index->cache_changed &&
4024 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4025 ret = error(_("merge: Unable to write new index file"));
4026 goto leave_merge;
4029 rollback_lock_file(&lock);
4030 if (ret)
4031 repo_rerere(r, opts->allow_rerere_auto);
4032 else
4034 * In case of problems, we now want to return a positive
4035 * value (a negative one would indicate that the `merge`
4036 * command needs to be rescheduled).
4038 fast_forward_edit:
4039 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4040 run_commit_flags);
4042 leave_merge:
4043 strbuf_release(&ref_name);
4044 rollback_lock_file(&lock);
4045 free_commit_list(to_merge);
4046 return ret;
4049 static int is_final_fixup(struct todo_list *todo_list)
4051 int i = todo_list->current;
4053 if (!is_fixup(todo_list->items[i].command))
4054 return 0;
4056 while (++i < todo_list->nr)
4057 if (is_fixup(todo_list->items[i].command))
4058 return 0;
4059 else if (!is_noop(todo_list->items[i].command))
4060 break;
4061 return 1;
4064 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4066 int i;
4068 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4069 if (!is_noop(todo_list->items[i].command))
4070 return todo_list->items[i].command;
4072 return -1;
4075 void create_autostash(struct repository *r, const char *path,
4076 const char *default_reflog_action)
4078 struct strbuf buf = STRBUF_INIT;
4079 struct lock_file lock_file = LOCK_INIT;
4080 int fd;
4082 fd = repo_hold_locked_index(r, &lock_file, 0);
4083 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4084 if (0 <= fd)
4085 repo_update_index_if_able(r, &lock_file);
4086 rollback_lock_file(&lock_file);
4088 if (has_unstaged_changes(r, 1) ||
4089 has_uncommitted_changes(r, 1)) {
4090 struct child_process stash = CHILD_PROCESS_INIT;
4091 struct object_id oid;
4093 strvec_pushl(&stash.args,
4094 "stash", "create", "autostash", NULL);
4095 stash.git_cmd = 1;
4096 stash.no_stdin = 1;
4097 strbuf_reset(&buf);
4098 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4099 die(_("Cannot autostash"));
4100 strbuf_trim_trailing_newline(&buf);
4101 if (get_oid(buf.buf, &oid))
4102 die(_("Unexpected stash response: '%s'"),
4103 buf.buf);
4104 strbuf_reset(&buf);
4105 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4107 if (safe_create_leading_directories_const(path))
4108 die(_("Could not create directory for '%s'"),
4109 path);
4110 write_file(path, "%s", oid_to_hex(&oid));
4111 printf(_("Created autostash: %s\n"), buf.buf);
4112 if (reset_head(r, NULL, "reset --hard",
4113 NULL, RESET_HEAD_HARD, NULL, NULL,
4114 default_reflog_action) < 0)
4115 die(_("could not reset --hard"));
4117 if (discard_index(r->index) < 0 ||
4118 repo_read_index(r) < 0)
4119 die(_("could not read index"));
4121 strbuf_release(&buf);
4124 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4126 struct child_process child = CHILD_PROCESS_INIT;
4127 int ret = 0;
4129 if (attempt_apply) {
4130 child.git_cmd = 1;
4131 child.no_stdout = 1;
4132 child.no_stderr = 1;
4133 strvec_push(&child.args, "stash");
4134 strvec_push(&child.args, "apply");
4135 strvec_push(&child.args, stash_oid);
4136 ret = run_command(&child);
4139 if (attempt_apply && !ret)
4140 fprintf(stderr, _("Applied autostash.\n"));
4141 else {
4142 struct child_process store = CHILD_PROCESS_INIT;
4144 store.git_cmd = 1;
4145 strvec_push(&store.args, "stash");
4146 strvec_push(&store.args, "store");
4147 strvec_push(&store.args, "-m");
4148 strvec_push(&store.args, "autostash");
4149 strvec_push(&store.args, "-q");
4150 strvec_push(&store.args, stash_oid);
4151 if (run_command(&store))
4152 ret = error(_("cannot store %s"), stash_oid);
4153 else
4154 fprintf(stderr,
4155 _("%s\n"
4156 "Your changes are safe in the stash.\n"
4157 "You can run \"git stash pop\" or"
4158 " \"git stash drop\" at any time.\n"),
4159 attempt_apply ?
4160 _("Applying autostash resulted in conflicts.") :
4161 _("Autostash exists; creating a new stash entry."));
4164 return ret;
4167 static int apply_save_autostash(const char *path, int attempt_apply)
4169 struct strbuf stash_oid = STRBUF_INIT;
4170 int ret = 0;
4172 if (!read_oneliner(&stash_oid, path,
4173 READ_ONELINER_SKIP_IF_EMPTY)) {
4174 strbuf_release(&stash_oid);
4175 return 0;
4177 strbuf_trim(&stash_oid);
4179 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4181 unlink(path);
4182 strbuf_release(&stash_oid);
4183 return ret;
4186 int save_autostash(const char *path)
4188 return apply_save_autostash(path, 0);
4191 int apply_autostash(const char *path)
4193 return apply_save_autostash(path, 1);
4196 int apply_autostash_oid(const char *stash_oid)
4198 return apply_save_autostash_oid(stash_oid, 1);
4201 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4202 const char *commit, const char *action)
4204 struct child_process cmd = CHILD_PROCESS_INIT;
4205 int ret;
4207 cmd.git_cmd = 1;
4209 strvec_push(&cmd.args, "checkout");
4210 strvec_push(&cmd.args, commit);
4211 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4213 if (opts->verbose)
4214 ret = run_command(&cmd);
4215 else
4216 ret = run_command_silent_on_success(&cmd);
4218 if (!ret)
4219 discard_index(r->index);
4221 return ret;
4224 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4225 const char *onto_name, const struct object_id *onto,
4226 const struct object_id *orig_head)
4228 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4230 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4231 apply_autostash(rebase_path_autostash());
4232 sequencer_remove_state(opts);
4233 return error(_("could not detach HEAD"));
4236 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4239 static int stopped_at_head(struct repository *r)
4241 struct object_id head;
4242 struct commit *commit;
4243 struct commit_message message;
4245 if (get_oid("HEAD", &head) ||
4246 !(commit = lookup_commit(r, &head)) ||
4247 parse_commit(commit) || get_message(commit, &message))
4248 fprintf(stderr, _("Stopped at HEAD\n"));
4249 else {
4250 fprintf(stderr, _("Stopped at %s\n"), message.label);
4251 free_message(commit, &message);
4253 return 0;
4257 static const char rescheduled_advice[] =
4258 N_("Could not execute the todo command\n"
4259 "\n"
4260 " %.*s"
4261 "\n"
4262 "It has been rescheduled; To edit the command before continuing, please\n"
4263 "edit the todo list first:\n"
4264 "\n"
4265 " git rebase --edit-todo\n"
4266 " git rebase --continue\n");
4268 static int pick_commits(struct repository *r,
4269 struct todo_list *todo_list,
4270 struct replay_opts *opts)
4272 int res = 0, reschedule = 0;
4273 char *prev_reflog_action;
4275 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4276 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4277 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4278 if (opts->allow_ff)
4279 assert(!(opts->signoff || opts->no_commit ||
4280 opts->record_origin || should_edit(opts) ||
4281 opts->committer_date_is_author_date ||
4282 opts->ignore_date));
4283 if (read_and_refresh_cache(r, opts))
4284 return -1;
4286 while (todo_list->current < todo_list->nr) {
4287 struct todo_item *item = todo_list->items + todo_list->current;
4288 const char *arg = todo_item_get_arg(todo_list, item);
4289 int check_todo = 0;
4291 if (save_todo(todo_list, opts))
4292 return -1;
4293 if (is_rebase_i(opts)) {
4294 if (item->command != TODO_COMMENT) {
4295 FILE *f = fopen(rebase_path_msgnum(), "w");
4297 todo_list->done_nr++;
4299 if (f) {
4300 fprintf(f, "%d\n", todo_list->done_nr);
4301 fclose(f);
4303 if (!opts->quiet)
4304 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4305 todo_list->done_nr,
4306 todo_list->total_nr,
4307 opts->verbose ? "\n" : "\r");
4309 unlink(rebase_path_message());
4310 unlink(rebase_path_author_script());
4311 unlink(rebase_path_stopped_sha());
4312 unlink(rebase_path_amend());
4313 unlink(git_path_merge_head(r));
4314 unlink(git_path_auto_merge(r));
4315 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4317 if (item->command == TODO_BREAK) {
4318 if (!opts->verbose)
4319 term_clear_line();
4320 return stopped_at_head(r);
4323 if (item->command <= TODO_SQUASH) {
4324 if (is_rebase_i(opts))
4325 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4326 command_to_string(item->command), NULL),
4328 res = do_pick_commit(r, item, opts,
4329 is_final_fixup(todo_list),
4330 &check_todo);
4331 if (is_rebase_i(opts))
4332 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4333 if (is_rebase_i(opts) && res < 0) {
4334 /* Reschedule */
4335 advise(_(rescheduled_advice),
4336 get_item_line_length(todo_list,
4337 todo_list->current),
4338 get_item_line(todo_list,
4339 todo_list->current));
4340 todo_list->current--;
4341 if (save_todo(todo_list, opts))
4342 return -1;
4344 if (item->command == TODO_EDIT) {
4345 struct commit *commit = item->commit;
4346 if (!res) {
4347 if (!opts->verbose)
4348 term_clear_line();
4349 fprintf(stderr,
4350 _("Stopped at %s... %.*s\n"),
4351 short_commit_name(commit),
4352 item->arg_len, arg);
4354 return error_with_patch(r, commit,
4355 arg, item->arg_len, opts, res, !res);
4357 if (is_rebase_i(opts) && !res)
4358 record_in_rewritten(&item->commit->object.oid,
4359 peek_command(todo_list, 1));
4360 if (res && is_fixup(item->command)) {
4361 if (res == 1)
4362 intend_to_amend();
4363 return error_failed_squash(r, item->commit, opts,
4364 item->arg_len, arg);
4365 } else if (res && is_rebase_i(opts) && item->commit) {
4366 int to_amend = 0;
4367 struct object_id oid;
4370 * If we are rewording and have either
4371 * fast-forwarded already, or are about to
4372 * create a new root commit, we want to amend,
4373 * otherwise we do not.
4375 if (item->command == TODO_REWORD &&
4376 !get_oid("HEAD", &oid) &&
4377 (oideq(&item->commit->object.oid, &oid) ||
4378 (opts->have_squash_onto &&
4379 oideq(&opts->squash_onto, &oid))))
4380 to_amend = 1;
4382 return res | error_with_patch(r, item->commit,
4383 arg, item->arg_len, opts,
4384 res, to_amend);
4386 } else if (item->command == TODO_EXEC) {
4387 char *end_of_arg = (char *)(arg + item->arg_len);
4388 int saved = *end_of_arg;
4390 if (!opts->verbose)
4391 term_clear_line();
4392 *end_of_arg = '\0';
4393 res = do_exec(r, arg);
4394 *end_of_arg = saved;
4396 if (res) {
4397 if (opts->reschedule_failed_exec)
4398 reschedule = 1;
4400 check_todo = 1;
4401 } else if (item->command == TODO_LABEL) {
4402 if ((res = do_label(r, arg, item->arg_len)))
4403 reschedule = 1;
4404 } else if (item->command == TODO_RESET) {
4405 if ((res = do_reset(r, arg, item->arg_len, opts)))
4406 reschedule = 1;
4407 } else if (item->command == TODO_MERGE) {
4408 if ((res = do_merge(r, item->commit,
4409 arg, item->arg_len,
4410 item->flags, opts)) < 0)
4411 reschedule = 1;
4412 else if (item->commit)
4413 record_in_rewritten(&item->commit->object.oid,
4414 peek_command(todo_list, 1));
4415 if (res > 0)
4416 /* failed with merge conflicts */
4417 return error_with_patch(r, item->commit,
4418 arg, item->arg_len,
4419 opts, res, 0);
4420 } else if (!is_noop(item->command))
4421 return error(_("unknown command %d"), item->command);
4423 if (reschedule) {
4424 advise(_(rescheduled_advice),
4425 get_item_line_length(todo_list,
4426 todo_list->current),
4427 get_item_line(todo_list, todo_list->current));
4428 todo_list->current--;
4429 if (save_todo(todo_list, opts))
4430 return -1;
4431 if (item->commit)
4432 return error_with_patch(r,
4433 item->commit,
4434 arg, item->arg_len,
4435 opts, res, 0);
4436 } else if (is_rebase_i(opts) && check_todo && !res) {
4437 struct stat st;
4439 if (stat(get_todo_path(opts), &st)) {
4440 res = error_errno(_("could not stat '%s'"),
4441 get_todo_path(opts));
4442 } else if (match_stat_data(&todo_list->stat, &st)) {
4443 /* Reread the todo file if it has changed. */
4444 todo_list_release(todo_list);
4445 if (read_populate_todo(r, todo_list, opts))
4446 res = -1; /* message was printed */
4447 /* `current` will be incremented below */
4448 todo_list->current = -1;
4452 todo_list->current++;
4453 if (res)
4454 return res;
4457 if (is_rebase_i(opts)) {
4458 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4459 struct stat st;
4461 /* Stopped in the middle, as planned? */
4462 if (todo_list->current < todo_list->nr)
4463 return 0;
4465 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4466 starts_with(head_ref.buf, "refs/")) {
4467 const char *msg;
4468 struct object_id head, orig;
4469 int res;
4471 if (get_oid("HEAD", &head)) {
4472 res = error(_("cannot read HEAD"));
4473 cleanup_head_ref:
4474 strbuf_release(&head_ref);
4475 strbuf_release(&buf);
4476 return res;
4478 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4479 get_oid_hex(buf.buf, &orig)) {
4480 res = error(_("could not read orig-head"));
4481 goto cleanup_head_ref;
4483 strbuf_reset(&buf);
4484 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4485 res = error(_("could not read 'onto'"));
4486 goto cleanup_head_ref;
4488 msg = reflog_message(opts, "finish", "%s onto %s",
4489 head_ref.buf, buf.buf);
4490 if (update_ref(msg, head_ref.buf, &head, &orig,
4491 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4492 res = error(_("could not update %s"),
4493 head_ref.buf);
4494 goto cleanup_head_ref;
4496 msg = reflog_message(opts, "finish", "returning to %s",
4497 head_ref.buf);
4498 if (create_symref("HEAD", head_ref.buf, msg)) {
4499 res = error(_("could not update HEAD to %s"),
4500 head_ref.buf);
4501 goto cleanup_head_ref;
4503 strbuf_reset(&buf);
4506 if (opts->verbose) {
4507 struct rev_info log_tree_opt;
4508 struct object_id orig, head;
4510 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4511 repo_init_revisions(r, &log_tree_opt, NULL);
4512 log_tree_opt.diff = 1;
4513 log_tree_opt.diffopt.output_format =
4514 DIFF_FORMAT_DIFFSTAT;
4515 log_tree_opt.disable_stdin = 1;
4517 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4518 !get_oid(buf.buf, &orig) &&
4519 !get_oid("HEAD", &head)) {
4520 diff_tree_oid(&orig, &head, "",
4521 &log_tree_opt.diffopt);
4522 log_tree_diff_flush(&log_tree_opt);
4525 flush_rewritten_pending();
4526 if (!stat(rebase_path_rewritten_list(), &st) &&
4527 st.st_size > 0) {
4528 struct child_process child = CHILD_PROCESS_INIT;
4529 const char *post_rewrite_hook =
4530 find_hook("post-rewrite");
4532 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4533 child.git_cmd = 1;
4534 strvec_push(&child.args, "notes");
4535 strvec_push(&child.args, "copy");
4536 strvec_push(&child.args, "--for-rewrite=rebase");
4537 /* we don't care if this copying failed */
4538 run_command(&child);
4540 if (post_rewrite_hook) {
4541 struct child_process hook = CHILD_PROCESS_INIT;
4543 hook.in = open(rebase_path_rewritten_list(),
4544 O_RDONLY);
4545 hook.stdout_to_stderr = 1;
4546 hook.trace2_hook_name = "post-rewrite";
4547 strvec_push(&hook.args, post_rewrite_hook);
4548 strvec_push(&hook.args, "rebase");
4549 /* we don't care if this hook failed */
4550 run_command(&hook);
4553 apply_autostash(rebase_path_autostash());
4555 if (!opts->quiet) {
4556 if (!opts->verbose)
4557 term_clear_line();
4558 fprintf(stderr,
4559 _("Successfully rebased and updated %s.\n"),
4560 head_ref.buf);
4563 strbuf_release(&buf);
4564 strbuf_release(&head_ref);
4568 * Sequence of picks finished successfully; cleanup by
4569 * removing the .git/sequencer directory
4571 return sequencer_remove_state(opts);
4574 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4576 struct strvec argv = STRVEC_INIT;
4577 int ret;
4579 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4580 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4581 return error(_("no cherry-pick or revert in progress"));
4583 strvec_push(&argv, "commit");
4586 * continue_single_pick() handles the case of recovering from a
4587 * conflict. should_edit() doesn't handle that case; for a conflict,
4588 * we want to edit if the user asked for it, or if they didn't specify
4589 * and stdin is a tty.
4591 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4593 * Include --cleanup=strip as well because we don't want the
4594 * "# Conflicts:" messages.
4596 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4598 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4599 strvec_clear(&argv);
4600 return ret;
4603 static int commit_staged_changes(struct repository *r,
4604 struct replay_opts *opts,
4605 struct todo_list *todo_list)
4607 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4608 unsigned int final_fixup = 0, is_clean;
4610 if (has_unstaged_changes(r, 1))
4611 return error(_("cannot rebase: You have unstaged changes."));
4613 is_clean = !has_uncommitted_changes(r, 0);
4615 if (file_exists(rebase_path_amend())) {
4616 struct strbuf rev = STRBUF_INIT;
4617 struct object_id head, to_amend;
4619 if (get_oid("HEAD", &head))
4620 return error(_("cannot amend non-existing commit"));
4621 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4622 return error(_("invalid file: '%s'"), rebase_path_amend());
4623 if (get_oid_hex(rev.buf, &to_amend))
4624 return error(_("invalid contents: '%s'"),
4625 rebase_path_amend());
4626 if (!is_clean && !oideq(&head, &to_amend))
4627 return error(_("\nYou have uncommitted changes in your "
4628 "working tree. Please, commit them\n"
4629 "first and then run 'git rebase "
4630 "--continue' again."));
4632 * When skipping a failed fixup/squash, we need to edit the
4633 * commit message, the current fixup list and count, and if it
4634 * was the last fixup/squash in the chain, we need to clean up
4635 * the commit message and if there was a squash, let the user
4636 * edit it.
4638 if (!is_clean || !opts->current_fixup_count)
4639 ; /* this is not the final fixup */
4640 else if (!oideq(&head, &to_amend) ||
4641 !file_exists(rebase_path_stopped_sha())) {
4642 /* was a final fixup or squash done manually? */
4643 if (!is_fixup(peek_command(todo_list, 0))) {
4644 unlink(rebase_path_fixup_msg());
4645 unlink(rebase_path_squash_msg());
4646 unlink(rebase_path_current_fixups());
4647 strbuf_reset(&opts->current_fixups);
4648 opts->current_fixup_count = 0;
4650 } else {
4651 /* we are in a fixup/squash chain */
4652 const char *p = opts->current_fixups.buf;
4653 int len = opts->current_fixups.len;
4655 opts->current_fixup_count--;
4656 if (!len)
4657 BUG("Incorrect current_fixups:\n%s", p);
4658 while (len && p[len - 1] != '\n')
4659 len--;
4660 strbuf_setlen(&opts->current_fixups, len);
4661 if (write_message(p, len, rebase_path_current_fixups(),
4662 0) < 0)
4663 return error(_("could not write file: '%s'"),
4664 rebase_path_current_fixups());
4667 * If a fixup/squash in a fixup/squash chain failed, the
4668 * commit message is already correct, no need to commit
4669 * it again.
4671 * Only if it is the final command in the fixup/squash
4672 * chain, and only if the chain is longer than a single
4673 * fixup/squash command (which was just skipped), do we
4674 * actually need to re-commit with a cleaned up commit
4675 * message.
4677 if (opts->current_fixup_count > 0 &&
4678 !is_fixup(peek_command(todo_list, 0))) {
4679 final_fixup = 1;
4681 * If there was not a single "squash" in the
4682 * chain, we only need to clean up the commit
4683 * message, no need to bother the user with
4684 * opening the commit message in the editor.
4686 if (!starts_with(p, "squash ") &&
4687 !strstr(p, "\nsquash "))
4688 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4689 } else if (is_fixup(peek_command(todo_list, 0))) {
4691 * We need to update the squash message to skip
4692 * the latest commit message.
4694 struct commit *commit;
4695 const char *path = rebase_path_squash_msg();
4696 const char *encoding = get_commit_output_encoding();
4698 if (parse_head(r, &commit) ||
4699 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4700 write_message(p, strlen(p), path, 0)) {
4701 unuse_commit_buffer(commit, p);
4702 return error(_("could not write file: "
4703 "'%s'"), path);
4705 unuse_commit_buffer(commit, p);
4709 strbuf_release(&rev);
4710 flags |= AMEND_MSG;
4713 if (is_clean) {
4714 if (refs_ref_exists(get_main_ref_store(r),
4715 "CHERRY_PICK_HEAD") &&
4716 refs_delete_ref(get_main_ref_store(r), "",
4717 "CHERRY_PICK_HEAD", NULL, 0))
4718 return error(_("could not remove CHERRY_PICK_HEAD"));
4719 if (!final_fixup)
4720 return 0;
4723 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4724 opts, flags))
4725 return error(_("could not commit staged changes."));
4726 unlink(rebase_path_amend());
4727 unlink(git_path_merge_head(r));
4728 unlink(git_path_auto_merge(r));
4729 if (final_fixup) {
4730 unlink(rebase_path_fixup_msg());
4731 unlink(rebase_path_squash_msg());
4733 if (opts->current_fixup_count > 0) {
4735 * Whether final fixup or not, we just cleaned up the commit
4736 * message...
4738 unlink(rebase_path_current_fixups());
4739 strbuf_reset(&opts->current_fixups);
4740 opts->current_fixup_count = 0;
4742 return 0;
4745 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4747 struct todo_list todo_list = TODO_LIST_INIT;
4748 int res;
4750 if (read_and_refresh_cache(r, opts))
4751 return -1;
4753 if (read_populate_opts(opts))
4754 return -1;
4755 if (is_rebase_i(opts)) {
4756 if ((res = read_populate_todo(r, &todo_list, opts)))
4757 goto release_todo_list;
4759 if (file_exists(rebase_path_dropped())) {
4760 if ((res = todo_list_check_against_backup(r, &todo_list)))
4761 goto release_todo_list;
4763 unlink(rebase_path_dropped());
4766 if (commit_staged_changes(r, opts, &todo_list)) {
4767 res = -1;
4768 goto release_todo_list;
4770 } else if (!file_exists(get_todo_path(opts)))
4771 return continue_single_pick(r, opts);
4772 else if ((res = read_populate_todo(r, &todo_list, opts)))
4773 goto release_todo_list;
4775 if (!is_rebase_i(opts)) {
4776 /* Verify that the conflict has been resolved */
4777 if (refs_ref_exists(get_main_ref_store(r),
4778 "CHERRY_PICK_HEAD") ||
4779 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4780 res = continue_single_pick(r, opts);
4781 if (res)
4782 goto release_todo_list;
4784 if (index_differs_from(r, "HEAD", NULL, 0)) {
4785 res = error_dirty_index(r, opts);
4786 goto release_todo_list;
4788 todo_list.current++;
4789 } else if (file_exists(rebase_path_stopped_sha())) {
4790 struct strbuf buf = STRBUF_INIT;
4791 struct object_id oid;
4793 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4794 READ_ONELINER_SKIP_IF_EMPTY) &&
4795 !get_oid_hex(buf.buf, &oid))
4796 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4797 strbuf_release(&buf);
4800 res = pick_commits(r, &todo_list, opts);
4801 release_todo_list:
4802 todo_list_release(&todo_list);
4803 return res;
4806 static int single_pick(struct repository *r,
4807 struct commit *cmit,
4808 struct replay_opts *opts)
4810 int check_todo;
4811 struct todo_item item;
4813 item.command = opts->action == REPLAY_PICK ?
4814 TODO_PICK : TODO_REVERT;
4815 item.commit = cmit;
4817 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4818 return do_pick_commit(r, &item, opts, 0, &check_todo);
4821 int sequencer_pick_revisions(struct repository *r,
4822 struct replay_opts *opts)
4824 struct todo_list todo_list = TODO_LIST_INIT;
4825 struct object_id oid;
4826 int i, res;
4828 assert(opts->revs);
4829 if (read_and_refresh_cache(r, opts))
4830 return -1;
4832 for (i = 0; i < opts->revs->pending.nr; i++) {
4833 struct object_id oid;
4834 const char *name = opts->revs->pending.objects[i].name;
4836 /* This happens when using --stdin. */
4837 if (!strlen(name))
4838 continue;
4840 if (!get_oid(name, &oid)) {
4841 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4842 enum object_type type = oid_object_info(r,
4843 &oid,
4844 NULL);
4845 return error(_("%s: can't cherry-pick a %s"),
4846 name, type_name(type));
4848 } else
4849 return error(_("%s: bad revision"), name);
4853 * If we were called as "git cherry-pick <commit>", just
4854 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4855 * REVERT_HEAD, and don't touch the sequencer state.
4856 * This means it is possible to cherry-pick in the middle
4857 * of a cherry-pick sequence.
4859 if (opts->revs->cmdline.nr == 1 &&
4860 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4861 opts->revs->no_walk &&
4862 !opts->revs->cmdline.rev->flags) {
4863 struct commit *cmit;
4864 if (prepare_revision_walk(opts->revs))
4865 return error(_("revision walk setup failed"));
4866 cmit = get_revision(opts->revs);
4867 if (!cmit)
4868 return error(_("empty commit set passed"));
4869 if (get_revision(opts->revs))
4870 BUG("unexpected extra commit from walk");
4871 return single_pick(r, cmit, opts);
4875 * Start a new cherry-pick/ revert sequence; but
4876 * first, make sure that an existing one isn't in
4877 * progress
4880 if (walk_revs_populate_todo(&todo_list, opts) ||
4881 create_seq_dir(r) < 0)
4882 return -1;
4883 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4884 return error(_("can't revert as initial commit"));
4885 if (save_head(oid_to_hex(&oid)))
4886 return -1;
4887 if (save_opts(opts))
4888 return -1;
4889 update_abort_safety_file();
4890 res = pick_commits(r, &todo_list, opts);
4891 todo_list_release(&todo_list);
4892 return res;
4895 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4897 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4898 struct strbuf sob = STRBUF_INIT;
4899 int has_footer;
4901 strbuf_addstr(&sob, sign_off_header);
4902 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4903 strbuf_addch(&sob, '\n');
4905 if (!ignore_footer)
4906 strbuf_complete_line(msgbuf);
4909 * If the whole message buffer is equal to the sob, pretend that we
4910 * found a conforming footer with a matching sob
4912 if (msgbuf->len - ignore_footer == sob.len &&
4913 !strncmp(msgbuf->buf, sob.buf, sob.len))
4914 has_footer = 3;
4915 else
4916 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4918 if (!has_footer) {
4919 const char *append_newlines = NULL;
4920 size_t len = msgbuf->len - ignore_footer;
4922 if (!len) {
4924 * The buffer is completely empty. Leave foom for
4925 * the title and body to be filled in by the user.
4927 append_newlines = "\n\n";
4928 } else if (len == 1) {
4930 * Buffer contains a single newline. Add another
4931 * so that we leave room for the title and body.
4933 append_newlines = "\n";
4934 } else if (msgbuf->buf[len - 2] != '\n') {
4936 * Buffer ends with a single newline. Add another
4937 * so that there is an empty line between the message
4938 * body and the sob.
4940 append_newlines = "\n";
4941 } /* else, the buffer already ends with two newlines. */
4943 if (append_newlines)
4944 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4945 append_newlines, strlen(append_newlines));
4948 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4949 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4950 sob.buf, sob.len);
4952 strbuf_release(&sob);
4955 struct labels_entry {
4956 struct hashmap_entry entry;
4957 char label[FLEX_ARRAY];
4960 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4961 const struct hashmap_entry *entry_or_key, const void *key)
4963 const struct labels_entry *a, *b;
4965 a = container_of(eptr, const struct labels_entry, entry);
4966 b = container_of(entry_or_key, const struct labels_entry, entry);
4968 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4971 struct string_entry {
4972 struct oidmap_entry entry;
4973 char string[FLEX_ARRAY];
4976 struct label_state {
4977 struct oidmap commit2label;
4978 struct hashmap labels;
4979 struct strbuf buf;
4982 static const char *label_oid(struct object_id *oid, const char *label,
4983 struct label_state *state)
4985 struct labels_entry *labels_entry;
4986 struct string_entry *string_entry;
4987 struct object_id dummy;
4988 int i;
4990 string_entry = oidmap_get(&state->commit2label, oid);
4991 if (string_entry)
4992 return string_entry->string;
4995 * For "uninteresting" commits, i.e. commits that are not to be
4996 * rebased, and which can therefore not be labeled, we use a unique
4997 * abbreviation of the commit name. This is slightly more complicated
4998 * than calling find_unique_abbrev() because we also need to make
4999 * sure that the abbreviation does not conflict with any other
5000 * label.
5002 * We disallow "interesting" commits to be labeled by a string that
5003 * is a valid full-length hash, to ensure that we always can find an
5004 * abbreviation for any uninteresting commit's names that does not
5005 * clash with any other label.
5007 strbuf_reset(&state->buf);
5008 if (!label) {
5009 char *p;
5011 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5012 label = p = state->buf.buf;
5014 find_unique_abbrev_r(p, oid, default_abbrev);
5017 * We may need to extend the abbreviated hash so that there is
5018 * no conflicting label.
5020 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5021 size_t i = strlen(p) + 1;
5023 oid_to_hex_r(p, oid);
5024 for (; i < the_hash_algo->hexsz; i++) {
5025 char save = p[i];
5026 p[i] = '\0';
5027 if (!hashmap_get_from_hash(&state->labels,
5028 strihash(p), p))
5029 break;
5030 p[i] = save;
5033 } else {
5034 struct strbuf *buf = &state->buf;
5037 * Sanitize labels by replacing non-alpha-numeric characters
5038 * (including white-space ones) by dashes, as they might be
5039 * illegal in file names (and hence in ref names).
5041 * Note that we retain non-ASCII UTF-8 characters (identified
5042 * via the most significant bit). They should be all acceptable
5043 * in file names. We do not validate the UTF-8 here, that's not
5044 * the job of this function.
5046 for (; *label; label++)
5047 if ((*label & 0x80) || isalnum(*label))
5048 strbuf_addch(buf, *label);
5049 /* avoid leading dash and double-dashes */
5050 else if (buf->len && buf->buf[buf->len - 1] != '-')
5051 strbuf_addch(buf, '-');
5052 if (!buf->len) {
5053 strbuf_addstr(buf, "rev-");
5054 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5056 label = buf->buf;
5058 if ((buf->len == the_hash_algo->hexsz &&
5059 !get_oid_hex(label, &dummy)) ||
5060 (buf->len == 1 && *label == '#') ||
5061 hashmap_get_from_hash(&state->labels,
5062 strihash(label), label)) {
5064 * If the label already exists, or if the label is a
5065 * valid full OID, or the label is a '#' (which we use
5066 * as a separator between merge heads and oneline), we
5067 * append a dash and a number to make it unique.
5069 size_t len = buf->len;
5071 for (i = 2; ; i++) {
5072 strbuf_setlen(buf, len);
5073 strbuf_addf(buf, "-%d", i);
5074 if (!hashmap_get_from_hash(&state->labels,
5075 strihash(buf->buf),
5076 buf->buf))
5077 break;
5080 label = buf->buf;
5084 FLEX_ALLOC_STR(labels_entry, label, label);
5085 hashmap_entry_init(&labels_entry->entry, strihash(label));
5086 hashmap_add(&state->labels, &labels_entry->entry);
5088 FLEX_ALLOC_STR(string_entry, string, label);
5089 oidcpy(&string_entry->entry.oid, oid);
5090 oidmap_put(&state->commit2label, string_entry);
5092 return string_entry->string;
5095 static int make_script_with_merges(struct pretty_print_context *pp,
5096 struct rev_info *revs, struct strbuf *out,
5097 unsigned flags)
5099 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5100 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5101 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5102 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5103 struct strbuf label = STRBUF_INIT;
5104 struct commit_list *commits = NULL, **tail = &commits, *iter;
5105 struct commit_list *tips = NULL, **tips_tail = &tips;
5106 struct commit *commit;
5107 struct oidmap commit2todo = OIDMAP_INIT;
5108 struct string_entry *entry;
5109 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5110 shown = OIDSET_INIT;
5111 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5113 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5114 const char *cmd_pick = abbr ? "p" : "pick",
5115 *cmd_label = abbr ? "l" : "label",
5116 *cmd_reset = abbr ? "t" : "reset",
5117 *cmd_merge = abbr ? "m" : "merge";
5119 oidmap_init(&commit2todo, 0);
5120 oidmap_init(&state.commit2label, 0);
5121 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5122 strbuf_init(&state.buf, 32);
5124 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5125 struct labels_entry *onto_label_entry;
5126 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5127 FLEX_ALLOC_STR(entry, string, "onto");
5128 oidcpy(&entry->entry.oid, oid);
5129 oidmap_put(&state.commit2label, entry);
5131 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5132 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5133 hashmap_add(&state.labels, &onto_label_entry->entry);
5137 * First phase:
5138 * - get onelines for all commits
5139 * - gather all branch tips (i.e. 2nd or later parents of merges)
5140 * - label all branch tips
5142 while ((commit = get_revision(revs))) {
5143 struct commit_list *to_merge;
5144 const char *p1, *p2;
5145 struct object_id *oid;
5146 int is_empty;
5148 tail = &commit_list_insert(commit, tail)->next;
5149 oidset_insert(&interesting, &commit->object.oid);
5151 is_empty = is_original_commit_empty(commit);
5152 if (!is_empty && (commit->object.flags & PATCHSAME))
5153 continue;
5154 if (is_empty && !keep_empty)
5155 continue;
5157 strbuf_reset(&oneline);
5158 pretty_print_commit(pp, commit, &oneline);
5160 to_merge = commit->parents ? commit->parents->next : NULL;
5161 if (!to_merge) {
5162 /* non-merge commit: easy case */
5163 strbuf_reset(&buf);
5164 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5165 oid_to_hex(&commit->object.oid),
5166 oneline.buf);
5167 if (is_empty)
5168 strbuf_addf(&buf, " %c empty",
5169 comment_line_char);
5171 FLEX_ALLOC_STR(entry, string, buf.buf);
5172 oidcpy(&entry->entry.oid, &commit->object.oid);
5173 oidmap_put(&commit2todo, entry);
5175 continue;
5178 /* Create a label */
5179 strbuf_reset(&label);
5180 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5181 (p1 = strchr(p1, '\'')) &&
5182 (p2 = strchr(++p1, '\'')))
5183 strbuf_add(&label, p1, p2 - p1);
5184 else if (skip_prefix(oneline.buf, "Merge pull request ",
5185 &p1) &&
5186 (p1 = strstr(p1, " from ")))
5187 strbuf_addstr(&label, p1 + strlen(" from "));
5188 else
5189 strbuf_addbuf(&label, &oneline);
5191 strbuf_reset(&buf);
5192 strbuf_addf(&buf, "%s -C %s",
5193 cmd_merge, oid_to_hex(&commit->object.oid));
5195 /* label the tips of merged branches */
5196 for (; to_merge; to_merge = to_merge->next) {
5197 oid = &to_merge->item->object.oid;
5198 strbuf_addch(&buf, ' ');
5200 if (!oidset_contains(&interesting, oid)) {
5201 strbuf_addstr(&buf, label_oid(oid, NULL,
5202 &state));
5203 continue;
5206 tips_tail = &commit_list_insert(to_merge->item,
5207 tips_tail)->next;
5209 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5211 strbuf_addf(&buf, " # %s", oneline.buf);
5213 FLEX_ALLOC_STR(entry, string, buf.buf);
5214 oidcpy(&entry->entry.oid, &commit->object.oid);
5215 oidmap_put(&commit2todo, entry);
5219 * Second phase:
5220 * - label branch points
5221 * - add HEAD to the branch tips
5223 for (iter = commits; iter; iter = iter->next) {
5224 struct commit_list *parent = iter->item->parents;
5225 for (; parent; parent = parent->next) {
5226 struct object_id *oid = &parent->item->object.oid;
5227 if (!oidset_contains(&interesting, oid))
5228 continue;
5229 if (oidset_insert(&child_seen, oid))
5230 label_oid(oid, "branch-point", &state);
5233 /* Add HEAD as implicit "tip of branch" */
5234 if (!iter->next)
5235 tips_tail = &commit_list_insert(iter->item,
5236 tips_tail)->next;
5240 * Third phase: output the todo list. This is a bit tricky, as we
5241 * want to avoid jumping back and forth between revisions. To
5242 * accomplish that goal, we walk backwards from the branch tips,
5243 * gathering commits not yet shown, reversing the list on the fly,
5244 * then outputting that list (labeling revisions as needed).
5246 strbuf_addf(out, "%s onto\n", cmd_label);
5247 for (iter = tips; iter; iter = iter->next) {
5248 struct commit_list *list = NULL, *iter2;
5250 commit = iter->item;
5251 if (oidset_contains(&shown, &commit->object.oid))
5252 continue;
5253 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5255 if (entry)
5256 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5257 else
5258 strbuf_addch(out, '\n');
5260 while (oidset_contains(&interesting, &commit->object.oid) &&
5261 !oidset_contains(&shown, &commit->object.oid)) {
5262 commit_list_insert(commit, &list);
5263 if (!commit->parents) {
5264 commit = NULL;
5265 break;
5267 commit = commit->parents->item;
5270 if (!commit)
5271 strbuf_addf(out, "%s %s\n", cmd_reset,
5272 rebase_cousins || root_with_onto ?
5273 "onto" : "[new root]");
5274 else {
5275 const char *to = NULL;
5277 entry = oidmap_get(&state.commit2label,
5278 &commit->object.oid);
5279 if (entry)
5280 to = entry->string;
5281 else if (!rebase_cousins)
5282 to = label_oid(&commit->object.oid, NULL,
5283 &state);
5285 if (!to || !strcmp(to, "onto"))
5286 strbuf_addf(out, "%s onto\n", cmd_reset);
5287 else {
5288 strbuf_reset(&oneline);
5289 pretty_print_commit(pp, commit, &oneline);
5290 strbuf_addf(out, "%s %s # %s\n",
5291 cmd_reset, to, oneline.buf);
5295 for (iter2 = list; iter2; iter2 = iter2->next) {
5296 struct object_id *oid = &iter2->item->object.oid;
5297 entry = oidmap_get(&commit2todo, oid);
5298 /* only show if not already upstream */
5299 if (entry)
5300 strbuf_addf(out, "%s\n", entry->string);
5301 entry = oidmap_get(&state.commit2label, oid);
5302 if (entry)
5303 strbuf_addf(out, "%s %s\n",
5304 cmd_label, entry->string);
5305 oidset_insert(&shown, oid);
5308 free_commit_list(list);
5311 free_commit_list(commits);
5312 free_commit_list(tips);
5314 strbuf_release(&label);
5315 strbuf_release(&oneline);
5316 strbuf_release(&buf);
5318 oidmap_free(&commit2todo, 1);
5319 oidmap_free(&state.commit2label, 1);
5320 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5321 strbuf_release(&state.buf);
5323 return 0;
5326 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5327 const char **argv, unsigned flags)
5329 char *format = NULL;
5330 struct pretty_print_context pp = {0};
5331 struct rev_info revs;
5332 struct commit *commit;
5333 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5334 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5335 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5336 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5338 repo_init_revisions(r, &revs, NULL);
5339 revs.verbose_header = 1;
5340 if (!rebase_merges)
5341 revs.max_parents = 1;
5342 revs.cherry_mark = !reapply_cherry_picks;
5343 revs.limited = 1;
5344 revs.reverse = 1;
5345 revs.right_only = 1;
5346 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5347 revs.topo_order = 1;
5349 revs.pretty_given = 1;
5350 git_config_get_string("rebase.instructionFormat", &format);
5351 if (!format || !*format) {
5352 free(format);
5353 format = xstrdup("%s");
5355 get_commit_format(format, &revs);
5356 free(format);
5357 pp.fmt = revs.commit_format;
5358 pp.output_encoding = get_log_output_encoding();
5360 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5361 return error(_("make_script: unhandled options"));
5363 if (prepare_revision_walk(&revs) < 0)
5364 return error(_("make_script: error preparing revisions"));
5366 if (rebase_merges)
5367 return make_script_with_merges(&pp, &revs, out, flags);
5369 while ((commit = get_revision(&revs))) {
5370 int is_empty = is_original_commit_empty(commit);
5372 if (!is_empty && (commit->object.flags & PATCHSAME))
5373 continue;
5374 if (is_empty && !keep_empty)
5375 continue;
5376 strbuf_addf(out, "%s %s ", insn,
5377 oid_to_hex(&commit->object.oid));
5378 pretty_print_commit(&pp, commit, out);
5379 if (is_empty)
5380 strbuf_addf(out, " %c empty", comment_line_char);
5381 strbuf_addch(out, '\n');
5383 return 0;
5387 * Add commands after pick and (series of) squash/fixup commands
5388 * in the todo list.
5390 void todo_list_add_exec_commands(struct todo_list *todo_list,
5391 struct string_list *commands)
5393 struct strbuf *buf = &todo_list->buf;
5394 size_t base_offset = buf->len;
5395 int i, insert, nr = 0, alloc = 0;
5396 struct todo_item *items = NULL, *base_items = NULL;
5398 CALLOC_ARRAY(base_items, commands->nr);
5399 for (i = 0; i < commands->nr; i++) {
5400 size_t command_len = strlen(commands->items[i].string);
5402 strbuf_addstr(buf, commands->items[i].string);
5403 strbuf_addch(buf, '\n');
5405 base_items[i].command = TODO_EXEC;
5406 base_items[i].offset_in_buf = base_offset;
5407 base_items[i].arg_offset = base_offset + strlen("exec ");
5408 base_items[i].arg_len = command_len - strlen("exec ");
5410 base_offset += command_len + 1;
5414 * Insert <commands> after every pick. Here, fixup/squash chains
5415 * are considered part of the pick, so we insert the commands *after*
5416 * those chains if there are any.
5418 * As we insert the exec commands immediately after rearranging
5419 * any fixups and before the user edits the list, a fixup chain
5420 * can never contain comments (any comments are empty picks that
5421 * have been commented out because the user did not specify
5422 * --keep-empty). So, it is safe to insert an exec command
5423 * without looking at the command following a comment.
5425 insert = 0;
5426 for (i = 0; i < todo_list->nr; i++) {
5427 enum todo_command command = todo_list->items[i].command;
5428 if (insert && !is_fixup(command)) {
5429 ALLOC_GROW(items, nr + commands->nr, alloc);
5430 COPY_ARRAY(items + nr, base_items, commands->nr);
5431 nr += commands->nr;
5433 insert = 0;
5436 ALLOC_GROW(items, nr + 1, alloc);
5437 items[nr++] = todo_list->items[i];
5439 if (command == TODO_PICK || command == TODO_MERGE)
5440 insert = 1;
5443 /* insert or append final <commands> */
5444 if (insert || nr == todo_list->nr) {
5445 ALLOC_GROW(items, nr + commands->nr, alloc);
5446 COPY_ARRAY(items + nr, base_items, commands->nr);
5447 nr += commands->nr;
5450 free(base_items);
5451 FREE_AND_NULL(todo_list->items);
5452 todo_list->items = items;
5453 todo_list->nr = nr;
5454 todo_list->alloc = alloc;
5457 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5458 struct strbuf *buf, int num, unsigned flags)
5460 struct todo_item *item;
5461 int i, max = todo_list->nr;
5463 if (num > 0 && num < max)
5464 max = num;
5466 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5467 char cmd;
5469 /* if the item is not a command write it and continue */
5470 if (item->command >= TODO_COMMENT) {
5471 strbuf_addf(buf, "%.*s\n", item->arg_len,
5472 todo_item_get_arg(todo_list, item));
5473 continue;
5476 /* add command to the buffer */
5477 cmd = command_to_char(item->command);
5478 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5479 strbuf_addch(buf, cmd);
5480 else
5481 strbuf_addstr(buf, command_to_string(item->command));
5483 /* add commit id */
5484 if (item->commit) {
5485 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5486 short_commit_name(item->commit) :
5487 oid_to_hex(&item->commit->object.oid);
5489 if (item->command == TODO_FIXUP) {
5490 if (item->flags & TODO_EDIT_FIXUP_MSG)
5491 strbuf_addstr(buf, " -c");
5492 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5493 strbuf_addstr(buf, " -C");
5497 if (item->command == TODO_MERGE) {
5498 if (item->flags & TODO_EDIT_MERGE_MSG)
5499 strbuf_addstr(buf, " -c");
5500 else
5501 strbuf_addstr(buf, " -C");
5504 strbuf_addf(buf, " %s", oid);
5507 /* add all the rest */
5508 if (!item->arg_len)
5509 strbuf_addch(buf, '\n');
5510 else
5511 strbuf_addf(buf, " %.*s\n", item->arg_len,
5512 todo_item_get_arg(todo_list, item));
5516 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5517 const char *file, const char *shortrevisions,
5518 const char *shortonto, int num, unsigned flags)
5520 int res;
5521 struct strbuf buf = STRBUF_INIT;
5523 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5524 if (flags & TODO_LIST_APPEND_TODO_HELP)
5525 append_todo_help(count_commands(todo_list),
5526 shortrevisions, shortonto, &buf);
5528 res = write_message(buf.buf, buf.len, file, 0);
5529 strbuf_release(&buf);
5531 return res;
5534 /* skip picking commits whose parents are unchanged */
5535 static int skip_unnecessary_picks(struct repository *r,
5536 struct todo_list *todo_list,
5537 struct object_id *base_oid)
5539 struct object_id *parent_oid;
5540 int i;
5542 for (i = 0; i < todo_list->nr; i++) {
5543 struct todo_item *item = todo_list->items + i;
5545 if (item->command >= TODO_NOOP)
5546 continue;
5547 if (item->command != TODO_PICK)
5548 break;
5549 if (parse_commit(item->commit)) {
5550 return error(_("could not parse commit '%s'"),
5551 oid_to_hex(&item->commit->object.oid));
5553 if (!item->commit->parents)
5554 break; /* root commit */
5555 if (item->commit->parents->next)
5556 break; /* merge commit */
5557 parent_oid = &item->commit->parents->item->object.oid;
5558 if (!oideq(parent_oid, base_oid))
5559 break;
5560 oidcpy(base_oid, &item->commit->object.oid);
5562 if (i > 0) {
5563 const char *done_path = rebase_path_done();
5565 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5566 error_errno(_("could not write to '%s'"), done_path);
5567 return -1;
5570 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5571 todo_list->nr -= i;
5572 todo_list->current = 0;
5573 todo_list->done_nr += i;
5575 if (is_fixup(peek_command(todo_list, 0)))
5576 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5579 return 0;
5582 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5583 const char *shortrevisions, const char *onto_name,
5584 struct commit *onto, const struct object_id *orig_head,
5585 struct string_list *commands, unsigned autosquash,
5586 struct todo_list *todo_list)
5588 char shortonto[GIT_MAX_HEXSZ + 1];
5589 const char *todo_file = rebase_path_todo();
5590 struct todo_list new_todo = TODO_LIST_INIT;
5591 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5592 struct object_id oid = onto->object.oid;
5593 int res;
5595 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5597 if (buf->len == 0) {
5598 struct todo_item *item = append_new_todo(todo_list);
5599 item->command = TODO_NOOP;
5600 item->commit = NULL;
5601 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5604 if (autosquash && todo_list_rearrange_squash(todo_list))
5605 return -1;
5607 if (commands->nr)
5608 todo_list_add_exec_commands(todo_list, commands);
5610 if (count_commands(todo_list) == 0) {
5611 apply_autostash(rebase_path_autostash());
5612 sequencer_remove_state(opts);
5614 return error(_("nothing to do"));
5617 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5618 shortonto, flags);
5619 if (res == -1)
5620 return -1;
5621 else if (res == -2) {
5622 apply_autostash(rebase_path_autostash());
5623 sequencer_remove_state(opts);
5625 return -1;
5626 } else if (res == -3) {
5627 apply_autostash(rebase_path_autostash());
5628 sequencer_remove_state(opts);
5629 todo_list_release(&new_todo);
5631 return error(_("nothing to do"));
5632 } else if (res == -4) {
5633 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5634 todo_list_release(&new_todo);
5636 return -1;
5639 /* Expand the commit IDs */
5640 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5641 strbuf_swap(&new_todo.buf, &buf2);
5642 strbuf_release(&buf2);
5643 new_todo.total_nr -= new_todo.nr;
5644 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5645 BUG("invalid todo list after expanding IDs:\n%s",
5646 new_todo.buf.buf);
5648 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5649 todo_list_release(&new_todo);
5650 return error(_("could not skip unnecessary pick commands"));
5653 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5654 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5655 todo_list_release(&new_todo);
5656 return error_errno(_("could not write '%s'"), todo_file);
5659 res = -1;
5661 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5662 goto cleanup;
5664 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5665 goto cleanup;
5667 todo_list_write_total_nr(&new_todo);
5668 res = pick_commits(r, &new_todo, opts);
5670 cleanup:
5671 todo_list_release(&new_todo);
5673 return res;
5676 struct subject2item_entry {
5677 struct hashmap_entry entry;
5678 int i;
5679 char subject[FLEX_ARRAY];
5682 static int subject2item_cmp(const void *fndata,
5683 const struct hashmap_entry *eptr,
5684 const struct hashmap_entry *entry_or_key,
5685 const void *key)
5687 const struct subject2item_entry *a, *b;
5689 a = container_of(eptr, const struct subject2item_entry, entry);
5690 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5692 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5695 define_commit_slab(commit_todo_item, struct todo_item *);
5697 static int skip_fixupish(const char *subject, const char **p) {
5698 return skip_prefix(subject, "fixup! ", p) ||
5699 skip_prefix(subject, "amend! ", p) ||
5700 skip_prefix(subject, "squash! ", p);
5704 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5705 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5706 * after the former, and change "pick" to "fixup"/"squash".
5708 * Note that if the config has specified a custom instruction format, each log
5709 * message will have to be retrieved from the commit (as the oneline in the
5710 * script cannot be trusted) in order to normalize the autosquash arrangement.
5712 int todo_list_rearrange_squash(struct todo_list *todo_list)
5714 struct hashmap subject2item;
5715 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5716 char **subjects;
5717 struct commit_todo_item commit_todo;
5718 struct todo_item *items = NULL;
5720 init_commit_todo_item(&commit_todo);
5722 * The hashmap maps onelines to the respective todo list index.
5724 * If any items need to be rearranged, the next[i] value will indicate
5725 * which item was moved directly after the i'th.
5727 * In that case, last[i] will indicate the index of the latest item to
5728 * be moved to appear after the i'th.
5730 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5731 ALLOC_ARRAY(next, todo_list->nr);
5732 ALLOC_ARRAY(tail, todo_list->nr);
5733 ALLOC_ARRAY(subjects, todo_list->nr);
5734 for (i = 0; i < todo_list->nr; i++) {
5735 struct strbuf buf = STRBUF_INIT;
5736 struct todo_item *item = todo_list->items + i;
5737 const char *commit_buffer, *subject, *p;
5738 size_t subject_len;
5739 int i2 = -1;
5740 struct subject2item_entry *entry;
5742 next[i] = tail[i] = -1;
5743 if (!item->commit || item->command == TODO_DROP) {
5744 subjects[i] = NULL;
5745 continue;
5748 if (is_fixup(item->command)) {
5749 clear_commit_todo_item(&commit_todo);
5750 return error(_("the script was already rearranged."));
5753 *commit_todo_item_at(&commit_todo, item->commit) = item;
5755 parse_commit(item->commit);
5756 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5757 find_commit_subject(commit_buffer, &subject);
5758 format_subject(&buf, subject, " ");
5759 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5760 unuse_commit_buffer(item->commit, commit_buffer);
5761 if (skip_fixupish(subject, &p)) {
5762 struct commit *commit2;
5764 for (;;) {
5765 while (isspace(*p))
5766 p++;
5767 if (!skip_fixupish(p, &p))
5768 break;
5771 entry = hashmap_get_entry_from_hash(&subject2item,
5772 strhash(p), p,
5773 struct subject2item_entry,
5774 entry);
5775 if (entry)
5776 /* found by title */
5777 i2 = entry->i;
5778 else if (!strchr(p, ' ') &&
5779 (commit2 =
5780 lookup_commit_reference_by_name(p)) &&
5781 *commit_todo_item_at(&commit_todo, commit2))
5782 /* found by commit name */
5783 i2 = *commit_todo_item_at(&commit_todo, commit2)
5784 - todo_list->items;
5785 else {
5786 /* copy can be a prefix of the commit subject */
5787 for (i2 = 0; i2 < i; i2++)
5788 if (subjects[i2] &&
5789 starts_with(subjects[i2], p))
5790 break;
5791 if (i2 == i)
5792 i2 = -1;
5795 if (i2 >= 0) {
5796 rearranged = 1;
5797 if (starts_with(subject, "fixup!")) {
5798 todo_list->items[i].command = TODO_FIXUP;
5799 } else if (starts_with(subject, "amend!")) {
5800 todo_list->items[i].command = TODO_FIXUP;
5801 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5802 } else {
5803 todo_list->items[i].command = TODO_SQUASH;
5805 if (tail[i2] < 0) {
5806 next[i] = next[i2];
5807 next[i2] = i;
5808 } else {
5809 next[i] = next[tail[i2]];
5810 next[tail[i2]] = i;
5812 tail[i2] = i;
5813 } else if (!hashmap_get_from_hash(&subject2item,
5814 strhash(subject), subject)) {
5815 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5816 entry->i = i;
5817 hashmap_entry_init(&entry->entry,
5818 strhash(entry->subject));
5819 hashmap_put(&subject2item, &entry->entry);
5823 if (rearranged) {
5824 for (i = 0; i < todo_list->nr; i++) {
5825 enum todo_command command = todo_list->items[i].command;
5826 int cur = i;
5829 * Initially, all commands are 'pick's. If it is a
5830 * fixup or a squash now, we have rearranged it.
5832 if (is_fixup(command))
5833 continue;
5835 while (cur >= 0) {
5836 ALLOC_GROW(items, nr + 1, alloc);
5837 items[nr++] = todo_list->items[cur];
5838 cur = next[cur];
5842 FREE_AND_NULL(todo_list->items);
5843 todo_list->items = items;
5844 todo_list->nr = nr;
5845 todo_list->alloc = alloc;
5848 free(next);
5849 free(tail);
5850 for (i = 0; i < todo_list->nr; i++)
5851 free(subjects[i]);
5852 free(subjects);
5853 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5855 clear_commit_todo_item(&commit_todo);
5857 return 0;
5860 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5862 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5863 struct object_id cherry_pick_head, rebase_head;
5865 if (file_exists(git_path_seq_dir()))
5866 *whence = FROM_CHERRY_PICK_MULTI;
5867 if (file_exists(rebase_path()) &&
5868 !get_oid("REBASE_HEAD", &rebase_head) &&
5869 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5870 oideq(&rebase_head, &cherry_pick_head))
5871 *whence = FROM_REBASE_PICK;
5872 else
5873 *whence = FROM_CHERRY_PICK_SINGLE;
5875 return 1;
5878 return 0;