Merge branch 'ds/maintenance-part-3'
[git.git] / sequencer.c
blob3dce6c963cec91e6b69de360d931a7d9e294db07
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "exec-cmd.h"
12 #include "utf8.h"
13 #include "cache-tree.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "rerere.h"
17 #include "merge-recursive.h"
18 #include "refs.h"
19 #include "strvec.h"
20 #include "quote.h"
21 #include "trailer.h"
22 #include "log-tree.h"
23 #include "wt-status.h"
24 #include "hashmap.h"
25 #include "notes-utils.h"
26 #include "sigchain.h"
27 #include "unpack-trees.h"
28 #include "worktree.h"
29 #include "oidmap.h"
30 #include "oidset.h"
31 #include "commit-slab.h"
32 #include "alias.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
35 #include "reset.h"
37 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
39 static const char sign_off_header[] = "Signed-off-by: ";
40 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
42 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
44 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
46 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
47 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
48 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
49 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
51 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
53 * The file containing rebase commands, comments, and empty lines.
54 * This file is created by "git rebase -i" then edited by the user. As
55 * the lines are processed, they are removed from the front of this
56 * file and written to the tail of 'done'.
58 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
59 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
61 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
64 * The rebase command lines that have already been processed. A line
65 * is moved here when it is first handled, before any associated user
66 * actions.
68 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
70 * The file to keep track of how many commands were already processed (e.g.
71 * for the prompt).
73 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
75 * The file to keep track of how many commands are to be processed in total
76 * (e.g. for the prompt).
78 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
80 * The commit message that is planned to be used for any changes that
81 * need to be committed following a user interaction.
83 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
85 * The file into which is accumulated the suggested commit message for
86 * squash/fixup commands. When the first of a series of squash/fixups
87 * is seen, the file is created and the commit message from the
88 * previous commit and from the first squash/fixup commit are written
89 * to it. The commit message for each subsequent squash/fixup commit
90 * is appended to the file as it is processed.
92 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
94 * If the current series of squash/fixups has not yet included a squash
95 * command, then this file exists and holds the commit message of the
96 * original "pick" commit. (If the series ends without a "squash"
97 * command, then this can be used as the commit message of the combined
98 * commit without opening the editor.)
100 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
102 * This file contains the list fixup/squash commands that have been
103 * accumulated into message-fixup or message-squash so far.
105 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
107 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
108 * GIT_AUTHOR_DATE that will be used for the commit that is currently
109 * being rebased.
111 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
113 * When an "edit" rebase command is being processed, the SHA1 of the
114 * commit to be edited is recorded in this file. When "git rebase
115 * --continue" is executed, if there are any staged changes then they
116 * will be amended to the HEAD commit, but only provided the HEAD
117 * commit is still the commit to be edited. When any other rebase
118 * command is processed, this file is deleted.
120 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
122 * When we stop at a given patch via the "edit" command, this file contains
123 * the commit object name of the corresponding patch.
125 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
127 * For the post-rewrite hook, we make a list of rewritten commits and
128 * their new sha1s. The rewritten-pending list keeps the sha1s of
129 * commits that have been processed, but not committed yet,
130 * e.g. because they are waiting for a 'squash' command.
132 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
133 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
134 "rebase-merge/rewritten-pending")
137 * The path of the file containing the OID of the "squash onto" commit, i.e.
138 * the dummy commit used for `reset [new root]`.
140 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
143 * The path of the file listing refs that need to be deleted after the rebase
144 * finishes. This is used by the `label` command to record the need for cleanup.
146 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
149 * The following files are written by git-rebase just after parsing the
150 * command-line.
152 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
153 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
154 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
155 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
156 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
157 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
158 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
159 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
160 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
161 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
162 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
163 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
164 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
165 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
166 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
167 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
169 static int git_sequencer_config(const char *k, const char *v, void *cb)
171 struct replay_opts *opts = cb;
172 int status;
174 if (!strcmp(k, "commit.cleanup")) {
175 const char *s;
177 status = git_config_string(&s, k, v);
178 if (status)
179 return status;
181 if (!strcmp(s, "verbatim")) {
182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "whitespace")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "strip")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
189 opts->explicit_cleanup = 1;
190 } else if (!strcmp(s, "scissors")) {
191 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
192 opts->explicit_cleanup = 1;
193 } else {
194 warning(_("invalid commit message cleanup mode '%s'"),
198 free((char *)s);
199 return status;
202 if (!strcmp(k, "commit.gpgsign")) {
203 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
204 return 0;
207 status = git_gpg_config(k, v, NULL);
208 if (status)
209 return status;
211 return git_diff_basic_config(k, v, NULL);
214 void sequencer_init_config(struct replay_opts *opts)
216 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
217 git_config(git_sequencer_config, opts);
220 static inline int is_rebase_i(const struct replay_opts *opts)
222 return opts->action == REPLAY_INTERACTIVE_REBASE;
225 static const char *get_dir(const struct replay_opts *opts)
227 if (is_rebase_i(opts))
228 return rebase_path();
229 return git_path_seq_dir();
232 static const char *get_todo_path(const struct replay_opts *opts)
234 if (is_rebase_i(opts))
235 return rebase_path_todo();
236 return git_path_todo_file();
240 * Returns 0 for non-conforming footer
241 * Returns 1 for conforming footer
242 * Returns 2 when sob exists within conforming footer
243 * Returns 3 when sob exists within conforming footer as last entry
245 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
246 size_t ignore_footer)
248 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
249 struct trailer_info info;
250 size_t i;
251 int found_sob = 0, found_sob_last = 0;
252 char saved_char;
254 opts.no_divider = 1;
256 if (ignore_footer) {
257 saved_char = sb->buf[sb->len - ignore_footer];
258 sb->buf[sb->len - ignore_footer] = '\0';
261 trailer_info_get(&info, sb->buf, &opts);
263 if (ignore_footer)
264 sb->buf[sb->len - ignore_footer] = saved_char;
266 if (info.trailer_start == info.trailer_end)
267 return 0;
269 for (i = 0; i < info.trailer_nr; i++)
270 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
271 found_sob = 1;
272 if (i == info.trailer_nr - 1)
273 found_sob_last = 1;
276 trailer_info_release(&info);
278 if (found_sob_last)
279 return 3;
280 if (found_sob)
281 return 2;
282 return 1;
285 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
287 static struct strbuf buf = STRBUF_INIT;
289 strbuf_reset(&buf);
290 if (opts->gpg_sign)
291 sq_quotef(&buf, "-S%s", opts->gpg_sign);
292 return buf.buf;
295 int sequencer_remove_state(struct replay_opts *opts)
297 struct strbuf buf = STRBUF_INIT;
298 int i, ret = 0;
300 if (is_rebase_i(opts) &&
301 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
302 char *p = buf.buf;
303 while (*p) {
304 char *eol = strchr(p, '\n');
305 if (eol)
306 *eol = '\0';
307 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
308 warning(_("could not delete '%s'"), p);
309 ret = -1;
311 if (!eol)
312 break;
313 p = eol + 1;
317 free(opts->gpg_sign);
318 free(opts->strategy);
319 for (i = 0; i < opts->xopts_nr; i++)
320 free(opts->xopts[i]);
321 free(opts->xopts);
322 strbuf_release(&opts->current_fixups);
324 strbuf_reset(&buf);
325 strbuf_addstr(&buf, get_dir(opts));
326 if (remove_dir_recursively(&buf, 0))
327 ret = error(_("could not remove '%s'"), buf.buf);
328 strbuf_release(&buf);
330 return ret;
333 static const char *action_name(const struct replay_opts *opts)
335 switch (opts->action) {
336 case REPLAY_REVERT:
337 return N_("revert");
338 case REPLAY_PICK:
339 return N_("cherry-pick");
340 case REPLAY_INTERACTIVE_REBASE:
341 return N_("rebase");
343 die(_("unknown action: %d"), opts->action);
346 struct commit_message {
347 char *parent_label;
348 char *label;
349 char *subject;
350 const char *message;
353 static const char *short_commit_name(struct commit *commit)
355 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
358 static int get_message(struct commit *commit, struct commit_message *out)
360 const char *abbrev, *subject;
361 int subject_len;
363 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
364 abbrev = short_commit_name(commit);
366 subject_len = find_commit_subject(out->message, &subject);
368 out->subject = xmemdupz(subject, subject_len);
369 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
370 out->parent_label = xstrfmt("parent of %s", out->label);
372 return 0;
375 static void free_message(struct commit *commit, struct commit_message *msg)
377 free(msg->parent_label);
378 free(msg->label);
379 free(msg->subject);
380 unuse_commit_buffer(commit, msg->message);
383 static void print_advice(struct repository *r, int show_hint,
384 struct replay_opts *opts)
386 char *msg = getenv("GIT_CHERRY_PICK_HELP");
388 if (msg) {
389 fprintf(stderr, "%s\n", msg);
391 * A conflict has occurred but the porcelain
392 * (typically rebase --interactive) wants to take care
393 * of the commit itself so remove CHERRY_PICK_HEAD
395 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
396 NULL, 0);
397 return;
400 if (show_hint) {
401 if (opts->no_commit)
402 advise(_("after resolving the conflicts, mark the corrected paths\n"
403 "with 'git add <paths>' or 'git rm <paths>'"));
404 else
405 advise(_("after resolving the conflicts, mark the corrected paths\n"
406 "with 'git add <paths>' or 'git rm <paths>'\n"
407 "and commit the result with 'git commit'"));
411 static int write_message(const void *buf, size_t len, const char *filename,
412 int append_eol)
414 struct lock_file msg_file = LOCK_INIT;
416 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
417 if (msg_fd < 0)
418 return error_errno(_("could not lock '%s'"), filename);
419 if (write_in_full(msg_fd, buf, len) < 0) {
420 error_errno(_("could not write to '%s'"), filename);
421 rollback_lock_file(&msg_file);
422 return -1;
424 if (append_eol && write(msg_fd, "\n", 1) < 0) {
425 error_errno(_("could not write eol to '%s'"), filename);
426 rollback_lock_file(&msg_file);
427 return -1;
429 if (commit_lock_file(&msg_file) < 0)
430 return error(_("failed to finalize '%s'"), filename);
432 return 0;
435 int read_oneliner(struct strbuf *buf,
436 const char *path, unsigned flags)
438 int orig_len = buf->len;
440 if (strbuf_read_file(buf, path, 0) < 0) {
441 if ((flags & READ_ONELINER_WARN_MISSING) ||
442 (errno != ENOENT && errno != ENOTDIR))
443 warning_errno(_("could not read '%s'"), path);
444 return 0;
447 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
448 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
449 --buf->len;
450 buf->buf[buf->len] = '\0';
453 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
454 return 0;
456 return 1;
459 static struct tree *empty_tree(struct repository *r)
461 return lookup_tree(r, the_hash_algo->empty_tree);
464 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
466 if (repo_read_index_unmerged(repo))
467 return error_resolve_conflict(_(action_name(opts)));
469 error(_("your local changes would be overwritten by %s."),
470 _(action_name(opts)));
472 if (advice_commit_before_merge)
473 advise(_("commit your changes or stash them to proceed."));
474 return -1;
477 static void update_abort_safety_file(void)
479 struct object_id head;
481 /* Do nothing on a single-pick */
482 if (!file_exists(git_path_seq_dir()))
483 return;
485 if (!get_oid("HEAD", &head))
486 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
487 else
488 write_file(git_path_abort_safety_file(), "%s", "");
491 static int fast_forward_to(struct repository *r,
492 const struct object_id *to,
493 const struct object_id *from,
494 int unborn,
495 struct replay_opts *opts)
497 struct ref_transaction *transaction;
498 struct strbuf sb = STRBUF_INIT;
499 struct strbuf err = STRBUF_INIT;
501 repo_read_index(r);
502 if (checkout_fast_forward(r, from, to, 1))
503 return -1; /* the callee should have complained already */
505 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
507 transaction = ref_transaction_begin(&err);
508 if (!transaction ||
509 ref_transaction_update(transaction, "HEAD",
510 to, unborn && !is_rebase_i(opts) ?
511 &null_oid : from,
512 0, sb.buf, &err) ||
513 ref_transaction_commit(transaction, &err)) {
514 ref_transaction_free(transaction);
515 error("%s", err.buf);
516 strbuf_release(&sb);
517 strbuf_release(&err);
518 return -1;
521 strbuf_release(&sb);
522 strbuf_release(&err);
523 ref_transaction_free(transaction);
524 update_abort_safety_file();
525 return 0;
528 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
529 int use_editor)
531 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
532 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
533 COMMIT_MSG_CLEANUP_SPACE;
534 else if (!strcmp(cleanup_arg, "verbatim"))
535 return COMMIT_MSG_CLEANUP_NONE;
536 else if (!strcmp(cleanup_arg, "whitespace"))
537 return COMMIT_MSG_CLEANUP_SPACE;
538 else if (!strcmp(cleanup_arg, "strip"))
539 return COMMIT_MSG_CLEANUP_ALL;
540 else if (!strcmp(cleanup_arg, "scissors"))
541 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
542 COMMIT_MSG_CLEANUP_SPACE;
543 else
544 die(_("Invalid cleanup mode %s"), cleanup_arg);
548 * NB using int rather than enum cleanup_mode to stop clang's
549 * -Wtautological-constant-out-of-range-compare complaining that the comparison
550 * is always true.
552 static const char *describe_cleanup_mode(int cleanup_mode)
554 static const char *modes[] = { "whitespace",
555 "verbatim",
556 "scissors",
557 "strip" };
559 if (cleanup_mode < ARRAY_SIZE(modes))
560 return modes[cleanup_mode];
562 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
565 void append_conflicts_hint(struct index_state *istate,
566 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
568 int i;
570 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
571 strbuf_addch(msgbuf, '\n');
572 wt_status_append_cut_line(msgbuf);
573 strbuf_addch(msgbuf, comment_line_char);
576 strbuf_addch(msgbuf, '\n');
577 strbuf_commented_addf(msgbuf, "Conflicts:\n");
578 for (i = 0; i < istate->cache_nr;) {
579 const struct cache_entry *ce = istate->cache[i++];
580 if (ce_stage(ce)) {
581 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
582 while (i < istate->cache_nr &&
583 !strcmp(ce->name, istate->cache[i]->name))
584 i++;
589 static int do_recursive_merge(struct repository *r,
590 struct commit *base, struct commit *next,
591 const char *base_label, const char *next_label,
592 struct object_id *head, struct strbuf *msgbuf,
593 struct replay_opts *opts)
595 struct merge_options o;
596 struct tree *next_tree, *base_tree, *head_tree;
597 int clean;
598 int i;
599 struct lock_file index_lock = LOCK_INIT;
601 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
602 return -1;
604 repo_read_index(r);
606 init_merge_options(&o, r);
607 o.ancestor = base ? base_label : "(empty tree)";
608 o.branch1 = "HEAD";
609 o.branch2 = next ? next_label : "(empty tree)";
610 if (is_rebase_i(opts))
611 o.buffer_output = 2;
612 o.show_rename_progress = 1;
614 head_tree = parse_tree_indirect(head);
615 next_tree = next ? get_commit_tree(next) : empty_tree(r);
616 base_tree = base ? get_commit_tree(base) : empty_tree(r);
618 for (i = 0; i < opts->xopts_nr; i++)
619 parse_merge_opt(&o, opts->xopts[i]);
621 clean = merge_trees(&o,
622 head_tree,
623 next_tree, base_tree);
624 if (is_rebase_i(opts) && clean <= 0)
625 fputs(o.obuf.buf, stdout);
626 strbuf_release(&o.obuf);
627 if (clean < 0) {
628 rollback_lock_file(&index_lock);
629 return clean;
632 if (write_locked_index(r->index, &index_lock,
633 COMMIT_LOCK | SKIP_IF_UNCHANGED))
635 * TRANSLATORS: %s will be "revert", "cherry-pick" or
636 * "rebase".
638 return error(_("%s: Unable to write new index file"),
639 _(action_name(opts)));
641 if (!clean)
642 append_conflicts_hint(r->index, msgbuf,
643 opts->default_msg_cleanup);
645 return !clean;
648 static struct object_id *get_cache_tree_oid(struct index_state *istate)
650 if (!istate->cache_tree)
651 istate->cache_tree = cache_tree();
653 if (!cache_tree_fully_valid(istate->cache_tree))
654 if (cache_tree_update(istate, 0)) {
655 error(_("unable to update cache tree"));
656 return NULL;
659 return &istate->cache_tree->oid;
662 static int is_index_unchanged(struct repository *r)
664 struct object_id head_oid, *cache_tree_oid;
665 struct commit *head_commit;
666 struct index_state *istate = r->index;
668 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
669 return error(_("could not resolve HEAD commit"));
671 head_commit = lookup_commit(r, &head_oid);
674 * If head_commit is NULL, check_commit, called from
675 * lookup_commit, would have indicated that head_commit is not
676 * a commit object already. parse_commit() will return failure
677 * without further complaints in such a case. Otherwise, if
678 * the commit is invalid, parse_commit() will complain. So
679 * there is nothing for us to say here. Just return failure.
681 if (parse_commit(head_commit))
682 return -1;
684 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
685 return -1;
687 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
690 static int write_author_script(const char *message)
692 struct strbuf buf = STRBUF_INIT;
693 const char *eol;
694 int res;
696 for (;;)
697 if (!*message || starts_with(message, "\n")) {
698 missing_author:
699 /* Missing 'author' line? */
700 unlink(rebase_path_author_script());
701 return 0;
702 } else if (skip_prefix(message, "author ", &message))
703 break;
704 else if ((eol = strchr(message, '\n')))
705 message = eol + 1;
706 else
707 goto missing_author;
709 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
710 while (*message && *message != '\n' && *message != '\r')
711 if (skip_prefix(message, " <", &message))
712 break;
713 else if (*message != '\'')
714 strbuf_addch(&buf, *(message++));
715 else
716 strbuf_addf(&buf, "'\\%c'", *(message++));
717 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
718 while (*message && *message != '\n' && *message != '\r')
719 if (skip_prefix(message, "> ", &message))
720 break;
721 else if (*message != '\'')
722 strbuf_addch(&buf, *(message++));
723 else
724 strbuf_addf(&buf, "'\\%c'", *(message++));
725 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
726 while (*message && *message != '\n' && *message != '\r')
727 if (*message != '\'')
728 strbuf_addch(&buf, *(message++));
729 else
730 strbuf_addf(&buf, "'\\%c'", *(message++));
731 strbuf_addch(&buf, '\'');
732 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
733 strbuf_release(&buf);
734 return res;
738 * Take a series of KEY='VALUE' lines where VALUE part is
739 * sq-quoted, and append <KEY, VALUE> at the end of the string list
741 static int parse_key_value_squoted(char *buf, struct string_list *list)
743 while (*buf) {
744 struct string_list_item *item;
745 char *np;
746 char *cp = strchr(buf, '=');
747 if (!cp) {
748 np = strchrnul(buf, '\n');
749 return error(_("no key present in '%.*s'"),
750 (int) (np - buf), buf);
752 np = strchrnul(cp, '\n');
753 *cp++ = '\0';
754 item = string_list_append(list, buf);
756 buf = np + (*np == '\n');
757 *np = '\0';
758 cp = sq_dequote(cp);
759 if (!cp)
760 return error(_("unable to dequote value of '%s'"),
761 item->string);
762 item->util = xstrdup(cp);
764 return 0;
768 * Reads and parses the state directory's "author-script" file, and sets name,
769 * email and date accordingly.
770 * Returns 0 on success, -1 if the file could not be parsed.
772 * The author script is of the format:
774 * GIT_AUTHOR_NAME='$author_name'
775 * GIT_AUTHOR_EMAIL='$author_email'
776 * GIT_AUTHOR_DATE='$author_date'
778 * where $author_name, $author_email and $author_date are quoted. We are strict
779 * with our parsing, as the file was meant to be eval'd in the now-removed
780 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
781 * from what this function expects, it is better to bail out than to do
782 * something that the user does not expect.
784 int read_author_script(const char *path, char **name, char **email, char **date,
785 int allow_missing)
787 struct strbuf buf = STRBUF_INIT;
788 struct string_list kv = STRING_LIST_INIT_DUP;
789 int retval = -1; /* assume failure */
790 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
792 if (strbuf_read_file(&buf, path, 256) <= 0) {
793 strbuf_release(&buf);
794 if (errno == ENOENT && allow_missing)
795 return 0;
796 else
797 return error_errno(_("could not open '%s' for reading"),
798 path);
801 if (parse_key_value_squoted(buf.buf, &kv))
802 goto finish;
804 for (i = 0; i < kv.nr; i++) {
805 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
806 if (name_i != -2)
807 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
808 else
809 name_i = i;
810 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
811 if (email_i != -2)
812 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
813 else
814 email_i = i;
815 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
816 if (date_i != -2)
817 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
818 else
819 date_i = i;
820 } else {
821 err = error(_("unknown variable '%s'"),
822 kv.items[i].string);
825 if (name_i == -2)
826 error(_("missing 'GIT_AUTHOR_NAME'"));
827 if (email_i == -2)
828 error(_("missing 'GIT_AUTHOR_EMAIL'"));
829 if (date_i == -2)
830 error(_("missing 'GIT_AUTHOR_DATE'"));
831 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
832 goto finish;
833 *name = kv.items[name_i].util;
834 *email = kv.items[email_i].util;
835 *date = kv.items[date_i].util;
836 retval = 0;
837 finish:
838 string_list_clear(&kv, !!retval);
839 strbuf_release(&buf);
840 return retval;
844 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
845 * file with shell quoting into struct strvec. Returns -1 on
846 * error, 0 otherwise.
848 static int read_env_script(struct strvec *env)
850 char *name, *email, *date;
852 if (read_author_script(rebase_path_author_script(),
853 &name, &email, &date, 0))
854 return -1;
856 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
857 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
858 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
859 free(name);
860 free(email);
861 free(date);
863 return 0;
866 static char *get_author(const char *message)
868 size_t len;
869 const char *a;
871 a = find_commit_header(message, "author", &len);
872 if (a)
873 return xmemdupz(a, len);
875 return NULL;
878 static const char *author_date_from_env_array(const struct strvec *env)
880 int i;
881 const char *date;
883 for (i = 0; i < env->nr; i++)
884 if (skip_prefix(env->v[i],
885 "GIT_AUTHOR_DATE=", &date))
886 return date;
888 * If GIT_AUTHOR_DATE is missing we should have already errored out when
889 * reading the script
891 BUG("GIT_AUTHOR_DATE missing from author script");
894 static const char staged_changes_advice[] =
895 N_("you have staged changes in your working tree\n"
896 "If these changes are meant to be squashed into the previous commit, run:\n"
897 "\n"
898 " git commit --amend %s\n"
899 "\n"
900 "If they are meant to go into a new commit, run:\n"
901 "\n"
902 " git commit %s\n"
903 "\n"
904 "In both cases, once you're done, continue with:\n"
905 "\n"
906 " git rebase --continue\n");
908 #define ALLOW_EMPTY (1<<0)
909 #define EDIT_MSG (1<<1)
910 #define AMEND_MSG (1<<2)
911 #define CLEANUP_MSG (1<<3)
912 #define VERIFY_MSG (1<<4)
913 #define CREATE_ROOT_COMMIT (1<<5)
915 static int run_command_silent_on_success(struct child_process *cmd)
917 struct strbuf buf = STRBUF_INIT;
918 int rc;
920 cmd->stdout_to_stderr = 1;
921 rc = pipe_command(cmd,
922 NULL, 0,
923 NULL, 0,
924 &buf, 0);
926 if (rc)
927 fputs(buf.buf, stderr);
928 strbuf_release(&buf);
929 return rc;
933 * If we are cherry-pick, and if the merge did not result in
934 * hand-editing, we will hit this commit and inherit the original
935 * author date and name.
937 * If we are revert, or if our cherry-pick results in a hand merge,
938 * we had better say that the current user is responsible for that.
940 * An exception is when run_git_commit() is called during an
941 * interactive rebase: in that case, we will want to retain the
942 * author metadata.
944 static int run_git_commit(const char *defmsg,
945 struct replay_opts *opts,
946 unsigned int flags)
948 struct child_process cmd = CHILD_PROCESS_INIT;
950 cmd.git_cmd = 1;
952 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
953 const char *gpg_opt = gpg_sign_opt_quoted(opts);
955 return error(_(staged_changes_advice),
956 gpg_opt, gpg_opt);
959 if (opts->committer_date_is_author_date)
960 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
961 opts->ignore_date ?
962 "" :
963 author_date_from_env_array(&cmd.env_array));
964 if (opts->ignore_date)
965 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
967 strvec_push(&cmd.args, "commit");
969 if (!(flags & VERIFY_MSG))
970 strvec_push(&cmd.args, "-n");
971 if ((flags & AMEND_MSG))
972 strvec_push(&cmd.args, "--amend");
973 if (opts->gpg_sign)
974 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
975 else
976 strvec_push(&cmd.args, "--no-gpg-sign");
977 if (defmsg)
978 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
979 else if (!(flags & EDIT_MSG))
980 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
981 if ((flags & CLEANUP_MSG))
982 strvec_push(&cmd.args, "--cleanup=strip");
983 if ((flags & EDIT_MSG))
984 strvec_push(&cmd.args, "-e");
985 else if (!(flags & CLEANUP_MSG) &&
986 !opts->signoff && !opts->record_origin &&
987 !opts->explicit_cleanup)
988 strvec_push(&cmd.args, "--cleanup=verbatim");
990 if ((flags & ALLOW_EMPTY))
991 strvec_push(&cmd.args, "--allow-empty");
993 if (!(flags & EDIT_MSG))
994 strvec_push(&cmd.args, "--allow-empty-message");
996 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
997 return run_command_silent_on_success(&cmd);
998 else
999 return run_command(&cmd);
1002 static int rest_is_empty(const struct strbuf *sb, int start)
1004 int i, eol;
1005 const char *nl;
1007 /* Check if the rest is just whitespace and Signed-off-by's. */
1008 for (i = start; i < sb->len; i++) {
1009 nl = memchr(sb->buf + i, '\n', sb->len - i);
1010 if (nl)
1011 eol = nl - sb->buf;
1012 else
1013 eol = sb->len;
1015 if (strlen(sign_off_header) <= eol - i &&
1016 starts_with(sb->buf + i, sign_off_header)) {
1017 i = eol;
1018 continue;
1020 while (i < eol)
1021 if (!isspace(sb->buf[i++]))
1022 return 0;
1025 return 1;
1028 void cleanup_message(struct strbuf *msgbuf,
1029 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1031 if (verbose || /* Truncate the message just before the diff, if any. */
1032 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1033 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1034 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1035 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1039 * Find out if the message in the strbuf contains only whitespace and
1040 * Signed-off-by lines.
1042 int message_is_empty(const struct strbuf *sb,
1043 enum commit_msg_cleanup_mode cleanup_mode)
1045 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1046 return 0;
1047 return rest_is_empty(sb, 0);
1051 * See if the user edited the message in the editor or left what
1052 * was in the template intact
1054 int template_untouched(const struct strbuf *sb, const char *template_file,
1055 enum commit_msg_cleanup_mode cleanup_mode)
1057 struct strbuf tmpl = STRBUF_INIT;
1058 const char *start;
1060 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1061 return 0;
1063 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1064 return 0;
1066 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1067 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1068 start = sb->buf;
1069 strbuf_release(&tmpl);
1070 return rest_is_empty(sb, start - sb->buf);
1073 int update_head_with_reflog(const struct commit *old_head,
1074 const struct object_id *new_head,
1075 const char *action, const struct strbuf *msg,
1076 struct strbuf *err)
1078 struct ref_transaction *transaction;
1079 struct strbuf sb = STRBUF_INIT;
1080 const char *nl;
1081 int ret = 0;
1083 if (action) {
1084 strbuf_addstr(&sb, action);
1085 strbuf_addstr(&sb, ": ");
1088 nl = strchr(msg->buf, '\n');
1089 if (nl) {
1090 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1091 } else {
1092 strbuf_addbuf(&sb, msg);
1093 strbuf_addch(&sb, '\n');
1096 transaction = ref_transaction_begin(err);
1097 if (!transaction ||
1098 ref_transaction_update(transaction, "HEAD", new_head,
1099 old_head ? &old_head->object.oid : &null_oid,
1100 0, sb.buf, err) ||
1101 ref_transaction_commit(transaction, err)) {
1102 ret = -1;
1104 ref_transaction_free(transaction);
1105 strbuf_release(&sb);
1107 return ret;
1110 static int run_rewrite_hook(const struct object_id *oldoid,
1111 const struct object_id *newoid)
1113 struct child_process proc = CHILD_PROCESS_INIT;
1114 const char *argv[3];
1115 int code;
1116 struct strbuf sb = STRBUF_INIT;
1118 argv[0] = find_hook("post-rewrite");
1119 if (!argv[0])
1120 return 0;
1122 argv[1] = "amend";
1123 argv[2] = NULL;
1125 proc.argv = argv;
1126 proc.in = -1;
1127 proc.stdout_to_stderr = 1;
1128 proc.trace2_hook_name = "post-rewrite";
1130 code = start_command(&proc);
1131 if (code)
1132 return code;
1133 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1134 sigchain_push(SIGPIPE, SIG_IGN);
1135 write_in_full(proc.in, sb.buf, sb.len);
1136 close(proc.in);
1137 strbuf_release(&sb);
1138 sigchain_pop(SIGPIPE);
1139 return finish_command(&proc);
1142 void commit_post_rewrite(struct repository *r,
1143 const struct commit *old_head,
1144 const struct object_id *new_head)
1146 struct notes_rewrite_cfg *cfg;
1148 cfg = init_copy_notes_for_rewrite("amend");
1149 if (cfg) {
1150 /* we are amending, so old_head is not NULL */
1151 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1152 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1154 run_rewrite_hook(&old_head->object.oid, new_head);
1157 static int run_prepare_commit_msg_hook(struct repository *r,
1158 struct strbuf *msg,
1159 const char *commit)
1161 int ret = 0;
1162 const char *name, *arg1 = NULL, *arg2 = NULL;
1164 name = git_path_commit_editmsg();
1165 if (write_message(msg->buf, msg->len, name, 0))
1166 return -1;
1168 if (commit) {
1169 arg1 = "commit";
1170 arg2 = commit;
1171 } else {
1172 arg1 = "message";
1174 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1175 arg1, arg2, NULL))
1176 ret = error(_("'prepare-commit-msg' hook failed"));
1178 return ret;
1181 static const char implicit_ident_advice_noconfig[] =
1182 N_("Your name and email address were configured automatically based\n"
1183 "on your username and hostname. Please check that they are accurate.\n"
1184 "You can suppress this message by setting them explicitly. Run the\n"
1185 "following command and follow the instructions in your editor to edit\n"
1186 "your configuration file:\n"
1187 "\n"
1188 " git config --global --edit\n"
1189 "\n"
1190 "After doing this, you may fix the identity used for this commit with:\n"
1191 "\n"
1192 " git commit --amend --reset-author\n");
1194 static const char implicit_ident_advice_config[] =
1195 N_("Your name and email address were configured automatically based\n"
1196 "on your username and hostname. Please check that they are accurate.\n"
1197 "You can suppress this message by setting them explicitly:\n"
1198 "\n"
1199 " git config --global user.name \"Your Name\"\n"
1200 " git config --global user.email you@example.com\n"
1201 "\n"
1202 "After doing this, you may fix the identity used for this commit with:\n"
1203 "\n"
1204 " git commit --amend --reset-author\n");
1206 static const char *implicit_ident_advice(void)
1208 char *user_config = expand_user_path("~/.gitconfig", 0);
1209 char *xdg_config = xdg_config_home("config");
1210 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1212 free(user_config);
1213 free(xdg_config);
1215 if (config_exists)
1216 return _(implicit_ident_advice_config);
1217 else
1218 return _(implicit_ident_advice_noconfig);
1222 void print_commit_summary(struct repository *r,
1223 const char *prefix,
1224 const struct object_id *oid,
1225 unsigned int flags)
1227 struct rev_info rev;
1228 struct commit *commit;
1229 struct strbuf format = STRBUF_INIT;
1230 const char *head;
1231 struct pretty_print_context pctx = {0};
1232 struct strbuf author_ident = STRBUF_INIT;
1233 struct strbuf committer_ident = STRBUF_INIT;
1235 commit = lookup_commit(r, oid);
1236 if (!commit)
1237 die(_("couldn't look up newly created commit"));
1238 if (parse_commit(commit))
1239 die(_("could not parse newly created commit"));
1241 strbuf_addstr(&format, "format:%h] %s");
1243 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1244 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1245 if (strbuf_cmp(&author_ident, &committer_ident)) {
1246 strbuf_addstr(&format, "\n Author: ");
1247 strbuf_addbuf_percentquote(&format, &author_ident);
1249 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1250 struct strbuf date = STRBUF_INIT;
1252 format_commit_message(commit, "%ad", &date, &pctx);
1253 strbuf_addstr(&format, "\n Date: ");
1254 strbuf_addbuf_percentquote(&format, &date);
1255 strbuf_release(&date);
1257 if (!committer_ident_sufficiently_given()) {
1258 strbuf_addstr(&format, "\n Committer: ");
1259 strbuf_addbuf_percentquote(&format, &committer_ident);
1260 if (advice_implicit_identity) {
1261 strbuf_addch(&format, '\n');
1262 strbuf_addstr(&format, implicit_ident_advice());
1265 strbuf_release(&author_ident);
1266 strbuf_release(&committer_ident);
1268 repo_init_revisions(r, &rev, prefix);
1269 setup_revisions(0, NULL, &rev, NULL);
1271 rev.diff = 1;
1272 rev.diffopt.output_format =
1273 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1275 rev.verbose_header = 1;
1276 rev.show_root_diff = 1;
1277 get_commit_format(format.buf, &rev);
1278 rev.always_show_header = 0;
1279 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1280 rev.diffopt.break_opt = 0;
1281 diff_setup_done(&rev.diffopt);
1283 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1284 if (!head)
1285 die_errno(_("unable to resolve HEAD after creating commit"));
1286 if (!strcmp(head, "HEAD"))
1287 head = _("detached HEAD");
1288 else
1289 skip_prefix(head, "refs/heads/", &head);
1290 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1291 _(" (root-commit)") : "");
1293 if (!log_tree_commit(&rev, commit)) {
1294 rev.always_show_header = 1;
1295 rev.use_terminator = 1;
1296 log_tree_commit(&rev, commit);
1299 strbuf_release(&format);
1302 static int parse_head(struct repository *r, struct commit **head)
1304 struct commit *current_head;
1305 struct object_id oid;
1307 if (get_oid("HEAD", &oid)) {
1308 current_head = NULL;
1309 } else {
1310 current_head = lookup_commit_reference(r, &oid);
1311 if (!current_head)
1312 return error(_("could not parse HEAD"));
1313 if (!oideq(&oid, &current_head->object.oid)) {
1314 warning(_("HEAD %s is not a commit!"),
1315 oid_to_hex(&oid));
1317 if (parse_commit(current_head))
1318 return error(_("could not parse HEAD commit"));
1320 *head = current_head;
1322 return 0;
1326 * Try to commit without forking 'git commit'. In some cases we need
1327 * to run 'git commit' to display an error message
1329 * Returns:
1330 * -1 - error unable to commit
1331 * 0 - success
1332 * 1 - run 'git commit'
1334 static int try_to_commit(struct repository *r,
1335 struct strbuf *msg, const char *author,
1336 struct replay_opts *opts, unsigned int flags,
1337 struct object_id *oid)
1339 struct object_id tree;
1340 struct commit *current_head = NULL;
1341 struct commit_list *parents = NULL;
1342 struct commit_extra_header *extra = NULL;
1343 struct strbuf err = STRBUF_INIT;
1344 struct strbuf commit_msg = STRBUF_INIT;
1345 char *amend_author = NULL;
1346 const char *committer = NULL;
1347 const char *hook_commit = NULL;
1348 enum commit_msg_cleanup_mode cleanup;
1349 int res = 0;
1351 if (parse_head(r, &current_head))
1352 return -1;
1354 if (flags & AMEND_MSG) {
1355 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1356 const char *out_enc = get_commit_output_encoding();
1357 const char *message = logmsg_reencode(current_head, NULL,
1358 out_enc);
1360 if (!msg) {
1361 const char *orig_message = NULL;
1363 find_commit_subject(message, &orig_message);
1364 msg = &commit_msg;
1365 strbuf_addstr(msg, orig_message);
1366 hook_commit = "HEAD";
1368 author = amend_author = get_author(message);
1369 unuse_commit_buffer(current_head, message);
1370 if (!author) {
1371 res = error(_("unable to parse commit author"));
1372 goto out;
1374 parents = copy_commit_list(current_head->parents);
1375 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1376 } else if (current_head &&
1377 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1378 commit_list_insert(current_head, &parents);
1381 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1382 res = error(_("git write-tree failed to write a tree"));
1383 goto out;
1386 if (!(flags & ALLOW_EMPTY)) {
1387 struct commit *first_parent = current_head;
1389 if (flags & AMEND_MSG) {
1390 if (current_head->parents) {
1391 first_parent = current_head->parents->item;
1392 if (repo_parse_commit(r, first_parent)) {
1393 res = error(_("could not parse HEAD commit"));
1394 goto out;
1396 } else {
1397 first_parent = NULL;
1400 if (oideq(first_parent
1401 ? get_commit_tree_oid(first_parent)
1402 : the_hash_algo->empty_tree,
1403 &tree)) {
1404 res = 1; /* run 'git commit' to display error message */
1405 goto out;
1409 if (find_hook("prepare-commit-msg")) {
1410 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1411 if (res)
1412 goto out;
1413 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1414 2048) < 0) {
1415 res = error_errno(_("unable to read commit message "
1416 "from '%s'"),
1417 git_path_commit_editmsg());
1418 goto out;
1420 msg = &commit_msg;
1423 if (flags & CLEANUP_MSG)
1424 cleanup = COMMIT_MSG_CLEANUP_ALL;
1425 else if ((opts->signoff || opts->record_origin) &&
1426 !opts->explicit_cleanup)
1427 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1428 else
1429 cleanup = opts->default_msg_cleanup;
1431 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1432 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1433 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1434 res = 1; /* run 'git commit' to display error message */
1435 goto out;
1438 if (opts->committer_date_is_author_date) {
1439 struct ident_split id;
1440 struct strbuf date = STRBUF_INIT;
1442 if (!opts->ignore_date) {
1443 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1444 res = error(_("invalid author identity '%s'"),
1445 author);
1446 goto out;
1448 if (!id.date_begin) {
1449 res = error(_(
1450 "corrupt author: missing date information"));
1451 goto out;
1453 strbuf_addf(&date, "@%.*s %.*s",
1454 (int)(id.date_end - id.date_begin),
1455 id.date_begin,
1456 (int)(id.tz_end - id.tz_begin),
1457 id.tz_begin);
1458 } else {
1459 reset_ident_date();
1461 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1462 getenv("GIT_COMMITTER_EMAIL"),
1463 WANT_COMMITTER_IDENT,
1464 opts->ignore_date ? NULL : date.buf,
1465 IDENT_STRICT);
1466 strbuf_release(&date);
1467 } else {
1468 reset_ident_date();
1471 if (opts->ignore_date) {
1472 struct ident_split id;
1473 char *name, *email;
1475 if (split_ident_line(&id, author, strlen(author)) < 0) {
1476 error(_("invalid author identity '%s'"), author);
1477 goto out;
1479 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1480 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1481 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1482 IDENT_STRICT);
1483 free(name);
1484 free(email);
1487 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1488 author, committer, opts->gpg_sign, extra)) {
1489 res = error(_("failed to write commit object"));
1490 goto out;
1493 if (update_head_with_reflog(current_head, oid,
1494 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1495 res = error("%s", err.buf);
1496 goto out;
1499 run_commit_hook(0, r->index_file, "post-commit", NULL);
1500 if (flags & AMEND_MSG)
1501 commit_post_rewrite(r, current_head, oid);
1503 out:
1504 free_commit_extra_headers(extra);
1505 strbuf_release(&err);
1506 strbuf_release(&commit_msg);
1507 free(amend_author);
1509 return res;
1512 static int write_rebase_head(struct object_id *oid)
1514 if (update_ref("rebase", "REBASE_HEAD", oid,
1515 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1516 return error(_("could not update %s"), "REBASE_HEAD");
1518 return 0;
1521 static int do_commit(struct repository *r,
1522 const char *msg_file, const char *author,
1523 struct replay_opts *opts, unsigned int flags,
1524 struct object_id *oid)
1526 int res = 1;
1528 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1529 struct object_id oid;
1530 struct strbuf sb = STRBUF_INIT;
1532 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1533 return error_errno(_("unable to read commit message "
1534 "from '%s'"),
1535 msg_file);
1537 res = try_to_commit(r, msg_file ? &sb : NULL,
1538 author, opts, flags, &oid);
1539 strbuf_release(&sb);
1540 if (!res) {
1541 refs_delete_ref(get_main_ref_store(r), "",
1542 "CHERRY_PICK_HEAD", NULL, 0);
1543 unlink(git_path_merge_msg(r));
1544 if (!is_rebase_i(opts))
1545 print_commit_summary(r, NULL, &oid,
1546 SUMMARY_SHOW_AUTHOR_DATE);
1547 return res;
1550 if (res == 1) {
1551 if (is_rebase_i(opts) && oid)
1552 if (write_rebase_head(oid))
1553 return -1;
1554 return run_git_commit(msg_file, opts, flags);
1557 return res;
1560 static int is_original_commit_empty(struct commit *commit)
1562 const struct object_id *ptree_oid;
1564 if (parse_commit(commit))
1565 return error(_("could not parse commit %s"),
1566 oid_to_hex(&commit->object.oid));
1567 if (commit->parents) {
1568 struct commit *parent = commit->parents->item;
1569 if (parse_commit(parent))
1570 return error(_("could not parse parent commit %s"),
1571 oid_to_hex(&parent->object.oid));
1572 ptree_oid = get_commit_tree_oid(parent);
1573 } else {
1574 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1577 return oideq(ptree_oid, get_commit_tree_oid(commit));
1581 * Should empty commits be allowed? Return status:
1582 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1583 * 0: Halt on empty commit
1584 * 1: Allow empty commit
1585 * 2: Drop empty commit
1587 static int allow_empty(struct repository *r,
1588 struct replay_opts *opts,
1589 struct commit *commit)
1591 int index_unchanged, originally_empty;
1594 * Four cases:
1596 * (1) we do not allow empty at all and error out.
1598 * (2) we allow ones that were initially empty, and
1599 * just drop the ones that become empty
1601 * (3) we allow ones that were initially empty, but
1602 * halt for the ones that become empty;
1604 * (4) we allow both.
1606 if (!opts->allow_empty)
1607 return 0; /* let "git commit" barf as necessary */
1609 index_unchanged = is_index_unchanged(r);
1610 if (index_unchanged < 0)
1611 return index_unchanged;
1612 if (!index_unchanged)
1613 return 0; /* we do not have to say --allow-empty */
1615 if (opts->keep_redundant_commits)
1616 return 1;
1618 originally_empty = is_original_commit_empty(commit);
1619 if (originally_empty < 0)
1620 return originally_empty;
1621 if (originally_empty)
1622 return 1;
1623 else if (opts->drop_redundant_commits)
1624 return 2;
1625 else
1626 return 0;
1629 static struct {
1630 char c;
1631 const char *str;
1632 } todo_command_info[] = {
1633 { 'p', "pick" },
1634 { 0, "revert" },
1635 { 'e', "edit" },
1636 { 'r', "reword" },
1637 { 'f', "fixup" },
1638 { 's', "squash" },
1639 { 'x', "exec" },
1640 { 'b', "break" },
1641 { 'l', "label" },
1642 { 't', "reset" },
1643 { 'm', "merge" },
1644 { 0, "noop" },
1645 { 'd', "drop" },
1646 { 0, NULL }
1649 static const char *command_to_string(const enum todo_command command)
1651 if (command < TODO_COMMENT)
1652 return todo_command_info[command].str;
1653 die(_("unknown command: %d"), command);
1656 static char command_to_char(const enum todo_command command)
1658 if (command < TODO_COMMENT)
1659 return todo_command_info[command].c;
1660 return comment_line_char;
1663 static int is_noop(const enum todo_command command)
1665 return TODO_NOOP <= command;
1668 static int is_fixup(enum todo_command command)
1670 return command == TODO_FIXUP || command == TODO_SQUASH;
1673 /* Does this command create a (non-merge) commit? */
1674 static int is_pick_or_similar(enum todo_command command)
1676 switch (command) {
1677 case TODO_PICK:
1678 case TODO_REVERT:
1679 case TODO_EDIT:
1680 case TODO_REWORD:
1681 case TODO_FIXUP:
1682 case TODO_SQUASH:
1683 return 1;
1684 default:
1685 return 0;
1689 static int update_squash_messages(struct repository *r,
1690 enum todo_command command,
1691 struct commit *commit,
1692 struct replay_opts *opts)
1694 struct strbuf buf = STRBUF_INIT;
1695 int res;
1696 const char *message, *body;
1697 const char *encoding = get_commit_output_encoding();
1699 if (opts->current_fixup_count > 0) {
1700 struct strbuf header = STRBUF_INIT;
1701 char *eol;
1703 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1704 return error(_("could not read '%s'"),
1705 rebase_path_squash_msg());
1707 eol = buf.buf[0] != comment_line_char ?
1708 buf.buf : strchrnul(buf.buf, '\n');
1710 strbuf_addf(&header, "%c ", comment_line_char);
1711 strbuf_addf(&header, _("This is a combination of %d commits."),
1712 opts->current_fixup_count + 2);
1713 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1714 strbuf_release(&header);
1715 } else {
1716 struct object_id head;
1717 struct commit *head_commit;
1718 const char *head_message, *body;
1720 if (get_oid("HEAD", &head))
1721 return error(_("need a HEAD to fixup"));
1722 if (!(head_commit = lookup_commit_reference(r, &head)))
1723 return error(_("could not read HEAD"));
1724 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1725 return error(_("could not read HEAD's commit message"));
1727 find_commit_subject(head_message, &body);
1728 if (write_message(body, strlen(body),
1729 rebase_path_fixup_msg(), 0)) {
1730 unuse_commit_buffer(head_commit, head_message);
1731 return error(_("cannot write '%s'"),
1732 rebase_path_fixup_msg());
1735 strbuf_addf(&buf, "%c ", comment_line_char);
1736 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1737 strbuf_addf(&buf, "\n%c ", comment_line_char);
1738 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1739 strbuf_addstr(&buf, "\n\n");
1740 strbuf_addstr(&buf, body);
1742 unuse_commit_buffer(head_commit, head_message);
1745 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1746 return error(_("could not read commit message of %s"),
1747 oid_to_hex(&commit->object.oid));
1748 find_commit_subject(message, &body);
1750 if (command == TODO_SQUASH) {
1751 unlink(rebase_path_fixup_msg());
1752 strbuf_addf(&buf, "\n%c ", comment_line_char);
1753 strbuf_addf(&buf, _("This is the commit message #%d:"),
1754 ++opts->current_fixup_count + 1);
1755 strbuf_addstr(&buf, "\n\n");
1756 strbuf_addstr(&buf, body);
1757 } else if (command == TODO_FIXUP) {
1758 strbuf_addf(&buf, "\n%c ", comment_line_char);
1759 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1760 ++opts->current_fixup_count + 1);
1761 strbuf_addstr(&buf, "\n\n");
1762 strbuf_add_commented_lines(&buf, body, strlen(body));
1763 } else
1764 return error(_("unknown command: %d"), command);
1765 unuse_commit_buffer(commit, message);
1767 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1768 strbuf_release(&buf);
1770 if (!res) {
1771 strbuf_addf(&opts->current_fixups, "%s%s %s",
1772 opts->current_fixups.len ? "\n" : "",
1773 command_to_string(command),
1774 oid_to_hex(&commit->object.oid));
1775 res = write_message(opts->current_fixups.buf,
1776 opts->current_fixups.len,
1777 rebase_path_current_fixups(), 0);
1780 return res;
1783 static void flush_rewritten_pending(void)
1785 struct strbuf buf = STRBUF_INIT;
1786 struct object_id newoid;
1787 FILE *out;
1789 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1790 !get_oid("HEAD", &newoid) &&
1791 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1792 char *bol = buf.buf, *eol;
1794 while (*bol) {
1795 eol = strchrnul(bol, '\n');
1796 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1797 bol, oid_to_hex(&newoid));
1798 if (!*eol)
1799 break;
1800 bol = eol + 1;
1802 fclose(out);
1803 unlink(rebase_path_rewritten_pending());
1805 strbuf_release(&buf);
1808 static void record_in_rewritten(struct object_id *oid,
1809 enum todo_command next_command)
1811 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1813 if (!out)
1814 return;
1816 fprintf(out, "%s\n", oid_to_hex(oid));
1817 fclose(out);
1819 if (!is_fixup(next_command))
1820 flush_rewritten_pending();
1823 static int do_pick_commit(struct repository *r,
1824 enum todo_command command,
1825 struct commit *commit,
1826 struct replay_opts *opts,
1827 int final_fixup, int *check_todo)
1829 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1830 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1831 struct object_id head;
1832 struct commit *base, *next, *parent;
1833 const char *base_label, *next_label;
1834 char *author = NULL;
1835 struct commit_message msg = { NULL, NULL, NULL, NULL };
1836 struct strbuf msgbuf = STRBUF_INIT;
1837 int res, unborn = 0, reword = 0, allow, drop_commit;
1839 if (opts->no_commit) {
1841 * We do not intend to commit immediately. We just want to
1842 * merge the differences in, so let's compute the tree
1843 * that represents the "current" state for merge-recursive
1844 * to work on.
1846 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1847 return error(_("your index file is unmerged."));
1848 } else {
1849 unborn = get_oid("HEAD", &head);
1850 /* Do we want to generate a root commit? */
1851 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1852 oideq(&head, &opts->squash_onto)) {
1853 if (is_fixup(command))
1854 return error(_("cannot fixup root commit"));
1855 flags |= CREATE_ROOT_COMMIT;
1856 unborn = 1;
1857 } else if (unborn)
1858 oidcpy(&head, the_hash_algo->empty_tree);
1859 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1860 NULL, 0))
1861 return error_dirty_index(r, opts);
1863 discard_index(r->index);
1865 if (!commit->parents)
1866 parent = NULL;
1867 else if (commit->parents->next) {
1868 /* Reverting or cherry-picking a merge commit */
1869 int cnt;
1870 struct commit_list *p;
1872 if (!opts->mainline)
1873 return error(_("commit %s is a merge but no -m option was given."),
1874 oid_to_hex(&commit->object.oid));
1876 for (cnt = 1, p = commit->parents;
1877 cnt != opts->mainline && p;
1878 cnt++)
1879 p = p->next;
1880 if (cnt != opts->mainline || !p)
1881 return error(_("commit %s does not have parent %d"),
1882 oid_to_hex(&commit->object.oid), opts->mainline);
1883 parent = p->item;
1884 } else if (1 < opts->mainline)
1886 * Non-first parent explicitly specified as mainline for
1887 * non-merge commit
1889 return error(_("commit %s does not have parent %d"),
1890 oid_to_hex(&commit->object.oid), opts->mainline);
1891 else
1892 parent = commit->parents->item;
1894 if (get_message(commit, &msg) != 0)
1895 return error(_("cannot get commit message for %s"),
1896 oid_to_hex(&commit->object.oid));
1898 if (opts->allow_ff && !is_fixup(command) &&
1899 ((parent && oideq(&parent->object.oid, &head)) ||
1900 (!parent && unborn))) {
1901 if (is_rebase_i(opts))
1902 write_author_script(msg.message);
1903 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1904 opts);
1905 if (res || command != TODO_REWORD)
1906 goto leave;
1907 reword = 1;
1908 msg_file = NULL;
1909 goto fast_forward_edit;
1911 if (parent && parse_commit(parent) < 0)
1912 /* TRANSLATORS: The first %s will be a "todo" command like
1913 "revert" or "pick", the second %s a SHA1. */
1914 return error(_("%s: cannot parse parent commit %s"),
1915 command_to_string(command),
1916 oid_to_hex(&parent->object.oid));
1919 * "commit" is an existing commit. We would want to apply
1920 * the difference it introduces since its first parent "prev"
1921 * on top of the current HEAD if we are cherry-pick. Or the
1922 * reverse of it if we are revert.
1925 if (command == TODO_REVERT) {
1926 base = commit;
1927 base_label = msg.label;
1928 next = parent;
1929 next_label = msg.parent_label;
1930 strbuf_addstr(&msgbuf, "Revert \"");
1931 strbuf_addstr(&msgbuf, msg.subject);
1932 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1933 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1935 if (commit->parents && commit->parents->next) {
1936 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1937 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1939 strbuf_addstr(&msgbuf, ".\n");
1940 } else {
1941 const char *p;
1943 base = parent;
1944 base_label = msg.parent_label;
1945 next = commit;
1946 next_label = msg.label;
1948 /* Append the commit log message to msgbuf. */
1949 if (find_commit_subject(msg.message, &p))
1950 strbuf_addstr(&msgbuf, p);
1952 if (opts->record_origin) {
1953 strbuf_complete_line(&msgbuf);
1954 if (!has_conforming_footer(&msgbuf, NULL, 0))
1955 strbuf_addch(&msgbuf, '\n');
1956 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1957 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1958 strbuf_addstr(&msgbuf, ")\n");
1960 if (!is_fixup(command))
1961 author = get_author(msg.message);
1964 if (command == TODO_REWORD)
1965 reword = 1;
1966 else if (is_fixup(command)) {
1967 if (update_squash_messages(r, command, commit, opts))
1968 return -1;
1969 flags |= AMEND_MSG;
1970 if (!final_fixup)
1971 msg_file = rebase_path_squash_msg();
1972 else if (file_exists(rebase_path_fixup_msg())) {
1973 flags |= CLEANUP_MSG;
1974 msg_file = rebase_path_fixup_msg();
1975 } else {
1976 const char *dest = git_path_squash_msg(r);
1977 unlink(dest);
1978 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1979 return error(_("could not rename '%s' to '%s'"),
1980 rebase_path_squash_msg(), dest);
1981 unlink(git_path_merge_msg(r));
1982 msg_file = dest;
1983 flags |= EDIT_MSG;
1987 if (opts->signoff && !is_fixup(command))
1988 append_signoff(&msgbuf, 0, 0);
1990 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1991 res = -1;
1992 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1993 res = do_recursive_merge(r, base, next, base_label, next_label,
1994 &head, &msgbuf, opts);
1995 if (res < 0)
1996 goto leave;
1998 res |= write_message(msgbuf.buf, msgbuf.len,
1999 git_path_merge_msg(r), 0);
2000 } else {
2001 struct commit_list *common = NULL;
2002 struct commit_list *remotes = NULL;
2004 res = write_message(msgbuf.buf, msgbuf.len,
2005 git_path_merge_msg(r), 0);
2007 commit_list_insert(base, &common);
2008 commit_list_insert(next, &remotes);
2009 res |= try_merge_command(r, opts->strategy,
2010 opts->xopts_nr, (const char **)opts->xopts,
2011 common, oid_to_hex(&head), remotes);
2012 free_commit_list(common);
2013 free_commit_list(remotes);
2015 strbuf_release(&msgbuf);
2018 * If the merge was clean or if it failed due to conflict, we write
2019 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2020 * However, if the merge did not even start, then we don't want to
2021 * write it at all.
2023 if ((command == TODO_PICK || command == TODO_REWORD ||
2024 command == TODO_EDIT) && !opts->no_commit &&
2025 (res == 0 || res == 1) &&
2026 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2027 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2028 res = -1;
2029 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2030 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2031 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2032 res = -1;
2034 if (res) {
2035 error(command == TODO_REVERT
2036 ? _("could not revert %s... %s")
2037 : _("could not apply %s... %s"),
2038 short_commit_name(commit), msg.subject);
2039 print_advice(r, res == 1, opts);
2040 repo_rerere(r, opts->allow_rerere_auto);
2041 goto leave;
2044 drop_commit = 0;
2045 allow = allow_empty(r, opts, commit);
2046 if (allow < 0) {
2047 res = allow;
2048 goto leave;
2049 } else if (allow == 1) {
2050 flags |= ALLOW_EMPTY;
2051 } else if (allow == 2) {
2052 drop_commit = 1;
2053 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2054 NULL, 0);
2055 unlink(git_path_merge_msg(r));
2056 fprintf(stderr,
2057 _("dropping %s %s -- patch contents already upstream\n"),
2058 oid_to_hex(&commit->object.oid), msg.subject);
2059 } /* else allow == 0 and there's nothing special to do */
2060 if (!opts->no_commit && !drop_commit) {
2061 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2062 res = do_commit(r, msg_file, author, opts, flags,
2063 commit? &commit->object.oid : NULL);
2064 else
2065 res = error(_("unable to parse commit author"));
2066 *check_todo = !!(flags & EDIT_MSG);
2067 if (!res && reword) {
2068 fast_forward_edit:
2069 res = run_git_commit(NULL, opts, EDIT_MSG |
2070 VERIFY_MSG | AMEND_MSG |
2071 (flags & ALLOW_EMPTY));
2072 *check_todo = 1;
2077 if (!res && final_fixup) {
2078 unlink(rebase_path_fixup_msg());
2079 unlink(rebase_path_squash_msg());
2080 unlink(rebase_path_current_fixups());
2081 strbuf_reset(&opts->current_fixups);
2082 opts->current_fixup_count = 0;
2085 leave:
2086 free_message(commit, &msg);
2087 free(author);
2088 update_abort_safety_file();
2090 return res;
2093 static int prepare_revs(struct replay_opts *opts)
2096 * picking (but not reverting) ranges (but not individual revisions)
2097 * should be done in reverse
2099 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2100 opts->revs->reverse ^= 1;
2102 if (prepare_revision_walk(opts->revs))
2103 return error(_("revision walk setup failed"));
2105 return 0;
2108 static int read_and_refresh_cache(struct repository *r,
2109 struct replay_opts *opts)
2111 struct lock_file index_lock = LOCK_INIT;
2112 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2113 if (repo_read_index(r) < 0) {
2114 rollback_lock_file(&index_lock);
2115 return error(_("git %s: failed to read the index"),
2116 _(action_name(opts)));
2118 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2119 if (index_fd >= 0) {
2120 if (write_locked_index(r->index, &index_lock,
2121 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2122 return error(_("git %s: failed to refresh the index"),
2123 _(action_name(opts)));
2126 return 0;
2129 enum todo_item_flags {
2130 TODO_EDIT_MERGE_MSG = 1
2133 void todo_list_release(struct todo_list *todo_list)
2135 strbuf_release(&todo_list->buf);
2136 FREE_AND_NULL(todo_list->items);
2137 todo_list->nr = todo_list->alloc = 0;
2140 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2142 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2143 todo_list->total_nr++;
2144 return todo_list->items + todo_list->nr++;
2147 const char *todo_item_get_arg(struct todo_list *todo_list,
2148 struct todo_item *item)
2150 return todo_list->buf.buf + item->arg_offset;
2153 static int is_command(enum todo_command command, const char **bol)
2155 const char *str = todo_command_info[command].str;
2156 const char nick = todo_command_info[command].c;
2157 const char *p = *bol + 1;
2159 return skip_prefix(*bol, str, bol) ||
2160 ((nick && **bol == nick) &&
2161 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2162 (*bol = p));
2165 static int parse_insn_line(struct repository *r, struct todo_item *item,
2166 const char *buf, const char *bol, char *eol)
2168 struct object_id commit_oid;
2169 char *end_of_object_name;
2170 int i, saved, status, padding;
2172 item->flags = 0;
2174 /* left-trim */
2175 bol += strspn(bol, " \t");
2177 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2178 item->command = TODO_COMMENT;
2179 item->commit = NULL;
2180 item->arg_offset = bol - buf;
2181 item->arg_len = eol - bol;
2182 return 0;
2185 for (i = 0; i < TODO_COMMENT; i++)
2186 if (is_command(i, &bol)) {
2187 item->command = i;
2188 break;
2190 if (i >= TODO_COMMENT)
2191 return -1;
2193 /* Eat up extra spaces/ tabs before object name */
2194 padding = strspn(bol, " \t");
2195 bol += padding;
2197 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2198 if (bol != eol)
2199 return error(_("%s does not accept arguments: '%s'"),
2200 command_to_string(item->command), bol);
2201 item->commit = NULL;
2202 item->arg_offset = bol - buf;
2203 item->arg_len = eol - bol;
2204 return 0;
2207 if (!padding)
2208 return error(_("missing arguments for %s"),
2209 command_to_string(item->command));
2211 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2212 item->command == TODO_RESET) {
2213 item->commit = NULL;
2214 item->arg_offset = bol - buf;
2215 item->arg_len = (int)(eol - bol);
2216 return 0;
2219 if (item->command == TODO_MERGE) {
2220 if (skip_prefix(bol, "-C", &bol))
2221 bol += strspn(bol, " \t");
2222 else if (skip_prefix(bol, "-c", &bol)) {
2223 bol += strspn(bol, " \t");
2224 item->flags |= TODO_EDIT_MERGE_MSG;
2225 } else {
2226 item->flags |= TODO_EDIT_MERGE_MSG;
2227 item->commit = NULL;
2228 item->arg_offset = bol - buf;
2229 item->arg_len = (int)(eol - bol);
2230 return 0;
2234 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2235 saved = *end_of_object_name;
2236 *end_of_object_name = '\0';
2237 status = get_oid(bol, &commit_oid);
2238 if (status < 0)
2239 error(_("could not parse '%s'"), bol); /* return later */
2240 *end_of_object_name = saved;
2242 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2243 item->arg_offset = bol - buf;
2244 item->arg_len = (int)(eol - bol);
2246 if (status < 0)
2247 return status;
2249 item->commit = lookup_commit_reference(r, &commit_oid);
2250 return item->commit ? 0 : -1;
2253 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2255 const char *todo_file, *bol;
2256 struct strbuf buf = STRBUF_INIT;
2257 int ret = 0;
2259 todo_file = git_path_todo_file();
2260 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2261 if (errno == ENOENT || errno == ENOTDIR)
2262 return -1;
2263 else
2264 return error_errno("unable to open '%s'", todo_file);
2266 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2267 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2268 *action = REPLAY_PICK;
2269 else if (is_command(TODO_REVERT, &bol) &&
2270 (*bol == ' ' || *bol == '\t'))
2271 *action = REPLAY_REVERT;
2272 else
2273 ret = -1;
2275 strbuf_release(&buf);
2277 return ret;
2280 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2281 struct todo_list *todo_list)
2283 struct todo_item *item;
2284 char *p = buf, *next_p;
2285 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2287 todo_list->current = todo_list->nr = 0;
2289 for (i = 1; *p; i++, p = next_p) {
2290 char *eol = strchrnul(p, '\n');
2292 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2294 if (p != eol && eol[-1] == '\r')
2295 eol--; /* strip Carriage Return */
2297 item = append_new_todo(todo_list);
2298 item->offset_in_buf = p - todo_list->buf.buf;
2299 if (parse_insn_line(r, item, buf, p, eol)) {
2300 res = error(_("invalid line %d: %.*s"),
2301 i, (int)(eol - p), p);
2302 item->command = TODO_COMMENT + 1;
2303 item->arg_offset = p - buf;
2304 item->arg_len = (int)(eol - p);
2305 item->commit = NULL;
2308 if (fixup_okay)
2309 ; /* do nothing */
2310 else if (is_fixup(item->command))
2311 return error(_("cannot '%s' without a previous commit"),
2312 command_to_string(item->command));
2313 else if (!is_noop(item->command))
2314 fixup_okay = 1;
2317 return res;
2320 static int count_commands(struct todo_list *todo_list)
2322 int count = 0, i;
2324 for (i = 0; i < todo_list->nr; i++)
2325 if (todo_list->items[i].command != TODO_COMMENT)
2326 count++;
2328 return count;
2331 static int get_item_line_offset(struct todo_list *todo_list, int index)
2333 return index < todo_list->nr ?
2334 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2337 static const char *get_item_line(struct todo_list *todo_list, int index)
2339 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2342 static int get_item_line_length(struct todo_list *todo_list, int index)
2344 return get_item_line_offset(todo_list, index + 1)
2345 - get_item_line_offset(todo_list, index);
2348 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2350 int fd;
2351 ssize_t len;
2353 fd = open(path, O_RDONLY);
2354 if (fd < 0)
2355 return error_errno(_("could not open '%s'"), path);
2356 len = strbuf_read(sb, fd, 0);
2357 close(fd);
2358 if (len < 0)
2359 return error(_("could not read '%s'."), path);
2360 return len;
2363 static int have_finished_the_last_pick(void)
2365 struct strbuf buf = STRBUF_INIT;
2366 const char *eol;
2367 const char *todo_path = git_path_todo_file();
2368 int ret = 0;
2370 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2371 if (errno == ENOENT) {
2372 return 0;
2373 } else {
2374 error_errno("unable to open '%s'", todo_path);
2375 return 0;
2378 /* If there is only one line then we are done */
2379 eol = strchr(buf.buf, '\n');
2380 if (!eol || !eol[1])
2381 ret = 1;
2383 strbuf_release(&buf);
2385 return ret;
2388 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2390 struct replay_opts opts = REPLAY_OPTS_INIT;
2391 int need_cleanup = 0;
2393 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2394 if (!refs_delete_ref(get_main_ref_store(r), "",
2395 "CHERRY_PICK_HEAD", NULL, 0) &&
2396 verbose)
2397 warning(_("cancelling a cherry picking in progress"));
2398 opts.action = REPLAY_PICK;
2399 need_cleanup = 1;
2402 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2403 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2404 NULL, 0) &&
2405 verbose)
2406 warning(_("cancelling a revert in progress"));
2407 opts.action = REPLAY_REVERT;
2408 need_cleanup = 1;
2411 if (!need_cleanup)
2412 return;
2414 if (!have_finished_the_last_pick())
2415 return;
2417 sequencer_remove_state(&opts);
2420 static void todo_list_write_total_nr(struct todo_list *todo_list)
2422 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2424 if (f) {
2425 fprintf(f, "%d\n", todo_list->total_nr);
2426 fclose(f);
2430 static int read_populate_todo(struct repository *r,
2431 struct todo_list *todo_list,
2432 struct replay_opts *opts)
2434 struct stat st;
2435 const char *todo_file = get_todo_path(opts);
2436 int res;
2438 strbuf_reset(&todo_list->buf);
2439 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2440 return -1;
2442 res = stat(todo_file, &st);
2443 if (res)
2444 return error(_("could not stat '%s'"), todo_file);
2445 fill_stat_data(&todo_list->stat, &st);
2447 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2448 if (res) {
2449 if (is_rebase_i(opts))
2450 return error(_("please fix this using "
2451 "'git rebase --edit-todo'."));
2452 return error(_("unusable instruction sheet: '%s'"), todo_file);
2455 if (!todo_list->nr &&
2456 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2457 return error(_("no commits parsed."));
2459 if (!is_rebase_i(opts)) {
2460 enum todo_command valid =
2461 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2462 int i;
2464 for (i = 0; i < todo_list->nr; i++)
2465 if (valid == todo_list->items[i].command)
2466 continue;
2467 else if (valid == TODO_PICK)
2468 return error(_("cannot cherry-pick during a revert."));
2469 else
2470 return error(_("cannot revert during a cherry-pick."));
2473 if (is_rebase_i(opts)) {
2474 struct todo_list done = TODO_LIST_INIT;
2476 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2477 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2478 todo_list->done_nr = count_commands(&done);
2479 else
2480 todo_list->done_nr = 0;
2482 todo_list->total_nr = todo_list->done_nr
2483 + count_commands(todo_list);
2484 todo_list_release(&done);
2486 todo_list_write_total_nr(todo_list);
2489 return 0;
2492 static int git_config_string_dup(char **dest,
2493 const char *var, const char *value)
2495 if (!value)
2496 return config_error_nonbool(var);
2497 free(*dest);
2498 *dest = xstrdup(value);
2499 return 0;
2502 static int populate_opts_cb(const char *key, const char *value, void *data)
2504 struct replay_opts *opts = data;
2505 int error_flag = 1;
2507 if (!value)
2508 error_flag = 0;
2509 else if (!strcmp(key, "options.no-commit"))
2510 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2511 else if (!strcmp(key, "options.edit"))
2512 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2513 else if (!strcmp(key, "options.allow-empty"))
2514 opts->allow_empty =
2515 git_config_bool_or_int(key, value, &error_flag);
2516 else if (!strcmp(key, "options.allow-empty-message"))
2517 opts->allow_empty_message =
2518 git_config_bool_or_int(key, value, &error_flag);
2519 else if (!strcmp(key, "options.keep-redundant-commits"))
2520 opts->keep_redundant_commits =
2521 git_config_bool_or_int(key, value, &error_flag);
2522 else if (!strcmp(key, "options.signoff"))
2523 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2524 else if (!strcmp(key, "options.record-origin"))
2525 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2526 else if (!strcmp(key, "options.allow-ff"))
2527 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2528 else if (!strcmp(key, "options.mainline"))
2529 opts->mainline = git_config_int(key, value);
2530 else if (!strcmp(key, "options.strategy"))
2531 git_config_string_dup(&opts->strategy, key, value);
2532 else if (!strcmp(key, "options.gpg-sign"))
2533 git_config_string_dup(&opts->gpg_sign, key, value);
2534 else if (!strcmp(key, "options.strategy-option")) {
2535 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2536 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2537 } else if (!strcmp(key, "options.allow-rerere-auto"))
2538 opts->allow_rerere_auto =
2539 git_config_bool_or_int(key, value, &error_flag) ?
2540 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2541 else if (!strcmp(key, "options.default-msg-cleanup")) {
2542 opts->explicit_cleanup = 1;
2543 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2544 } else
2545 return error(_("invalid key: %s"), key);
2547 if (!error_flag)
2548 return error(_("invalid value for %s: %s"), key, value);
2550 return 0;
2553 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2555 int i;
2556 char *strategy_opts_string = raw_opts;
2558 if (*strategy_opts_string == ' ')
2559 strategy_opts_string++;
2561 opts->xopts_nr = split_cmdline(strategy_opts_string,
2562 (const char ***)&opts->xopts);
2563 for (i = 0; i < opts->xopts_nr; i++) {
2564 const char *arg = opts->xopts[i];
2566 skip_prefix(arg, "--", &arg);
2567 opts->xopts[i] = xstrdup(arg);
2571 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2573 strbuf_reset(buf);
2574 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2575 return;
2576 opts->strategy = strbuf_detach(buf, NULL);
2577 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2578 return;
2580 parse_strategy_opts(opts, buf->buf);
2583 static int read_populate_opts(struct replay_opts *opts)
2585 if (is_rebase_i(opts)) {
2586 struct strbuf buf = STRBUF_INIT;
2587 int ret = 0;
2589 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2590 READ_ONELINER_SKIP_IF_EMPTY)) {
2591 if (!starts_with(buf.buf, "-S"))
2592 strbuf_reset(&buf);
2593 else {
2594 free(opts->gpg_sign);
2595 opts->gpg_sign = xstrdup(buf.buf + 2);
2597 strbuf_reset(&buf);
2600 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2601 READ_ONELINER_SKIP_IF_EMPTY)) {
2602 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2603 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2604 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2605 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2606 strbuf_reset(&buf);
2609 if (file_exists(rebase_path_verbose()))
2610 opts->verbose = 1;
2612 if (file_exists(rebase_path_quiet()))
2613 opts->quiet = 1;
2615 if (file_exists(rebase_path_signoff())) {
2616 opts->allow_ff = 0;
2617 opts->signoff = 1;
2620 if (file_exists(rebase_path_cdate_is_adate())) {
2621 opts->allow_ff = 0;
2622 opts->committer_date_is_author_date = 1;
2625 if (file_exists(rebase_path_ignore_date())) {
2626 opts->allow_ff = 0;
2627 opts->ignore_date = 1;
2630 if (file_exists(rebase_path_reschedule_failed_exec()))
2631 opts->reschedule_failed_exec = 1;
2633 if (file_exists(rebase_path_drop_redundant_commits()))
2634 opts->drop_redundant_commits = 1;
2636 if (file_exists(rebase_path_keep_redundant_commits()))
2637 opts->keep_redundant_commits = 1;
2639 read_strategy_opts(opts, &buf);
2640 strbuf_reset(&buf);
2642 if (read_oneliner(&opts->current_fixups,
2643 rebase_path_current_fixups(),
2644 READ_ONELINER_SKIP_IF_EMPTY)) {
2645 const char *p = opts->current_fixups.buf;
2646 opts->current_fixup_count = 1;
2647 while ((p = strchr(p, '\n'))) {
2648 opts->current_fixup_count++;
2649 p++;
2653 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2654 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2655 ret = error(_("unusable squash-onto"));
2656 goto done_rebase_i;
2658 opts->have_squash_onto = 1;
2661 done_rebase_i:
2662 strbuf_release(&buf);
2663 return ret;
2666 if (!file_exists(git_path_opts_file()))
2667 return 0;
2669 * The function git_parse_source(), called from git_config_from_file(),
2670 * may die() in case of a syntactically incorrect file. We do not care
2671 * about this case, though, because we wrote that file ourselves, so we
2672 * are pretty certain that it is syntactically correct.
2674 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2675 return error(_("malformed options sheet: '%s'"),
2676 git_path_opts_file());
2677 return 0;
2680 static void write_strategy_opts(struct replay_opts *opts)
2682 int i;
2683 struct strbuf buf = STRBUF_INIT;
2685 for (i = 0; i < opts->xopts_nr; ++i)
2686 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2688 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2689 strbuf_release(&buf);
2692 int write_basic_state(struct replay_opts *opts, const char *head_name,
2693 struct commit *onto, const struct object_id *orig_head)
2695 if (head_name)
2696 write_file(rebase_path_head_name(), "%s\n", head_name);
2697 if (onto)
2698 write_file(rebase_path_onto(), "%s\n",
2699 oid_to_hex(&onto->object.oid));
2700 if (orig_head)
2701 write_file(rebase_path_orig_head(), "%s\n",
2702 oid_to_hex(orig_head));
2704 if (opts->quiet)
2705 write_file(rebase_path_quiet(), "%s", "");
2706 if (opts->verbose)
2707 write_file(rebase_path_verbose(), "%s", "");
2708 if (opts->strategy)
2709 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2710 if (opts->xopts_nr > 0)
2711 write_strategy_opts(opts);
2713 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2714 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2715 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2716 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2718 if (opts->gpg_sign)
2719 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2720 if (opts->signoff)
2721 write_file(rebase_path_signoff(), "--signoff\n");
2722 if (opts->drop_redundant_commits)
2723 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2724 if (opts->keep_redundant_commits)
2725 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2726 if (opts->committer_date_is_author_date)
2727 write_file(rebase_path_cdate_is_adate(), "%s", "");
2728 if (opts->ignore_date)
2729 write_file(rebase_path_ignore_date(), "%s", "");
2730 if (opts->reschedule_failed_exec)
2731 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2733 return 0;
2736 static int walk_revs_populate_todo(struct todo_list *todo_list,
2737 struct replay_opts *opts)
2739 enum todo_command command = opts->action == REPLAY_PICK ?
2740 TODO_PICK : TODO_REVERT;
2741 const char *command_string = todo_command_info[command].str;
2742 const char *encoding;
2743 struct commit *commit;
2745 if (prepare_revs(opts))
2746 return -1;
2748 encoding = get_log_output_encoding();
2750 while ((commit = get_revision(opts->revs))) {
2751 struct todo_item *item = append_new_todo(todo_list);
2752 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2753 const char *subject;
2754 int subject_len;
2756 item->command = command;
2757 item->commit = commit;
2758 item->arg_offset = 0;
2759 item->arg_len = 0;
2760 item->offset_in_buf = todo_list->buf.len;
2761 subject_len = find_commit_subject(commit_buffer, &subject);
2762 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2763 short_commit_name(commit), subject_len, subject);
2764 unuse_commit_buffer(commit, commit_buffer);
2767 if (!todo_list->nr)
2768 return error(_("empty commit set passed"));
2770 return 0;
2773 static int create_seq_dir(struct repository *r)
2775 enum replay_action action;
2776 const char *in_progress_error = NULL;
2777 const char *in_progress_advice = NULL;
2778 unsigned int advise_skip =
2779 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
2780 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
2782 if (!sequencer_get_last_command(r, &action)) {
2783 switch (action) {
2784 case REPLAY_REVERT:
2785 in_progress_error = _("revert is already in progress");
2786 in_progress_advice =
2787 _("try \"git revert (--continue | %s--abort | --quit)\"");
2788 break;
2789 case REPLAY_PICK:
2790 in_progress_error = _("cherry-pick is already in progress");
2791 in_progress_advice =
2792 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2793 break;
2794 default:
2795 BUG("unexpected action in create_seq_dir");
2798 if (in_progress_error) {
2799 error("%s", in_progress_error);
2800 if (advice_sequencer_in_use)
2801 advise(in_progress_advice,
2802 advise_skip ? "--skip | " : "");
2803 return -1;
2805 if (mkdir(git_path_seq_dir(), 0777) < 0)
2806 return error_errno(_("could not create sequencer directory '%s'"),
2807 git_path_seq_dir());
2809 return 0;
2812 static int save_head(const char *head)
2814 struct lock_file head_lock = LOCK_INIT;
2815 struct strbuf buf = STRBUF_INIT;
2816 int fd;
2817 ssize_t written;
2819 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2820 if (fd < 0)
2821 return error_errno(_("could not lock HEAD"));
2822 strbuf_addf(&buf, "%s\n", head);
2823 written = write_in_full(fd, buf.buf, buf.len);
2824 strbuf_release(&buf);
2825 if (written < 0) {
2826 error_errno(_("could not write to '%s'"), git_path_head_file());
2827 rollback_lock_file(&head_lock);
2828 return -1;
2830 if (commit_lock_file(&head_lock) < 0)
2831 return error(_("failed to finalize '%s'"), git_path_head_file());
2832 return 0;
2835 static int rollback_is_safe(void)
2837 struct strbuf sb = STRBUF_INIT;
2838 struct object_id expected_head, actual_head;
2840 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2841 strbuf_trim(&sb);
2842 if (get_oid_hex(sb.buf, &expected_head)) {
2843 strbuf_release(&sb);
2844 die(_("could not parse %s"), git_path_abort_safety_file());
2846 strbuf_release(&sb);
2848 else if (errno == ENOENT)
2849 oidclr(&expected_head);
2850 else
2851 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2853 if (get_oid("HEAD", &actual_head))
2854 oidclr(&actual_head);
2856 return oideq(&actual_head, &expected_head);
2859 static int reset_merge(const struct object_id *oid)
2861 int ret;
2862 struct strvec argv = STRVEC_INIT;
2864 strvec_pushl(&argv, "reset", "--merge", NULL);
2866 if (!is_null_oid(oid))
2867 strvec_push(&argv, oid_to_hex(oid));
2869 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
2870 strvec_clear(&argv);
2872 return ret;
2875 static int rollback_single_pick(struct repository *r)
2877 struct object_id head_oid;
2879 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
2880 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
2881 return error(_("no cherry-pick or revert in progress"));
2882 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2883 return error(_("cannot resolve HEAD"));
2884 if (is_null_oid(&head_oid))
2885 return error(_("cannot abort from a branch yet to be born"));
2886 return reset_merge(&head_oid);
2889 static int skip_single_pick(void)
2891 struct object_id head;
2893 if (read_ref_full("HEAD", 0, &head, NULL))
2894 return error(_("cannot resolve HEAD"));
2895 return reset_merge(&head);
2898 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2900 FILE *f;
2901 struct object_id oid;
2902 struct strbuf buf = STRBUF_INIT;
2903 const char *p;
2905 f = fopen(git_path_head_file(), "r");
2906 if (!f && errno == ENOENT) {
2908 * There is no multiple-cherry-pick in progress.
2909 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2910 * a single-cherry-pick in progress, abort that.
2912 return rollback_single_pick(r);
2914 if (!f)
2915 return error_errno(_("cannot open '%s'"), git_path_head_file());
2916 if (strbuf_getline_lf(&buf, f)) {
2917 error(_("cannot read '%s': %s"), git_path_head_file(),
2918 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2919 fclose(f);
2920 goto fail;
2922 fclose(f);
2923 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2924 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2925 git_path_head_file());
2926 goto fail;
2928 if (is_null_oid(&oid)) {
2929 error(_("cannot abort from a branch yet to be born"));
2930 goto fail;
2933 if (!rollback_is_safe()) {
2934 /* Do not error, just do not rollback */
2935 warning(_("You seem to have moved HEAD. "
2936 "Not rewinding, check your HEAD!"));
2937 } else
2938 if (reset_merge(&oid))
2939 goto fail;
2940 strbuf_release(&buf);
2941 return sequencer_remove_state(opts);
2942 fail:
2943 strbuf_release(&buf);
2944 return -1;
2947 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2949 enum replay_action action = -1;
2950 sequencer_get_last_command(r, &action);
2953 * Check whether the subcommand requested to skip the commit is actually
2954 * in progress and that it's safe to skip the commit.
2956 * opts->action tells us which subcommand requested to skip the commit.
2957 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2958 * action is in progress and we can skip the commit.
2960 * Otherwise we check that the last instruction was related to the
2961 * particular subcommand we're trying to execute and barf if that's not
2962 * the case.
2964 * Finally we check that the rollback is "safe", i.e., has the HEAD
2965 * moved? In this case, it doesn't make sense to "reset the merge" and
2966 * "skip the commit" as the user already handled this by committing. But
2967 * we'd not want to barf here, instead give advice on how to proceed. We
2968 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2969 * it gets removed when the user commits, so if it still exists we're
2970 * sure the user can't have committed before.
2972 switch (opts->action) {
2973 case REPLAY_REVERT:
2974 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2975 if (action != REPLAY_REVERT)
2976 return error(_("no revert in progress"));
2977 if (!rollback_is_safe())
2978 goto give_advice;
2980 break;
2981 case REPLAY_PICK:
2982 if (!refs_ref_exists(get_main_ref_store(r),
2983 "CHERRY_PICK_HEAD")) {
2984 if (action != REPLAY_PICK)
2985 return error(_("no cherry-pick in progress"));
2986 if (!rollback_is_safe())
2987 goto give_advice;
2989 break;
2990 default:
2991 BUG("unexpected action in sequencer_skip");
2994 if (skip_single_pick())
2995 return error(_("failed to skip the commit"));
2996 if (!is_directory(git_path_seq_dir()))
2997 return 0;
2999 return sequencer_continue(r, opts);
3001 give_advice:
3002 error(_("there is nothing to skip"));
3004 if (advice_resolve_conflict) {
3005 advise(_("have you committed already?\n"
3006 "try \"git %s --continue\""),
3007 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3009 return -1;
3012 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3014 struct lock_file todo_lock = LOCK_INIT;
3015 const char *todo_path = get_todo_path(opts);
3016 int next = todo_list->current, offset, fd;
3019 * rebase -i writes "git-rebase-todo" without the currently executing
3020 * command, appending it to "done" instead.
3022 if (is_rebase_i(opts))
3023 next++;
3025 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3026 if (fd < 0)
3027 return error_errno(_("could not lock '%s'"), todo_path);
3028 offset = get_item_line_offset(todo_list, next);
3029 if (write_in_full(fd, todo_list->buf.buf + offset,
3030 todo_list->buf.len - offset) < 0)
3031 return error_errno(_("could not write to '%s'"), todo_path);
3032 if (commit_lock_file(&todo_lock) < 0)
3033 return error(_("failed to finalize '%s'"), todo_path);
3035 if (is_rebase_i(opts) && next > 0) {
3036 const char *done = rebase_path_done();
3037 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3038 int ret = 0;
3040 if (fd < 0)
3041 return 0;
3042 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3043 get_item_line_length(todo_list, next - 1))
3044 < 0)
3045 ret = error_errno(_("could not write to '%s'"), done);
3046 if (close(fd) < 0)
3047 ret = error_errno(_("failed to finalize '%s'"), done);
3048 return ret;
3050 return 0;
3053 static int save_opts(struct replay_opts *opts)
3055 const char *opts_file = git_path_opts_file();
3056 int res = 0;
3058 if (opts->no_commit)
3059 res |= git_config_set_in_file_gently(opts_file,
3060 "options.no-commit", "true");
3061 if (opts->edit)
3062 res |= git_config_set_in_file_gently(opts_file,
3063 "options.edit", "true");
3064 if (opts->allow_empty)
3065 res |= git_config_set_in_file_gently(opts_file,
3066 "options.allow-empty", "true");
3067 if (opts->allow_empty_message)
3068 res |= git_config_set_in_file_gently(opts_file,
3069 "options.allow-empty-message", "true");
3070 if (opts->keep_redundant_commits)
3071 res |= git_config_set_in_file_gently(opts_file,
3072 "options.keep-redundant-commits", "true");
3073 if (opts->signoff)
3074 res |= git_config_set_in_file_gently(opts_file,
3075 "options.signoff", "true");
3076 if (opts->record_origin)
3077 res |= git_config_set_in_file_gently(opts_file,
3078 "options.record-origin", "true");
3079 if (opts->allow_ff)
3080 res |= git_config_set_in_file_gently(opts_file,
3081 "options.allow-ff", "true");
3082 if (opts->mainline) {
3083 struct strbuf buf = STRBUF_INIT;
3084 strbuf_addf(&buf, "%d", opts->mainline);
3085 res |= git_config_set_in_file_gently(opts_file,
3086 "options.mainline", buf.buf);
3087 strbuf_release(&buf);
3089 if (opts->strategy)
3090 res |= git_config_set_in_file_gently(opts_file,
3091 "options.strategy", opts->strategy);
3092 if (opts->gpg_sign)
3093 res |= git_config_set_in_file_gently(opts_file,
3094 "options.gpg-sign", opts->gpg_sign);
3095 if (opts->xopts) {
3096 int i;
3097 for (i = 0; i < opts->xopts_nr; i++)
3098 res |= git_config_set_multivar_in_file_gently(opts_file,
3099 "options.strategy-option",
3100 opts->xopts[i], "^$", 0);
3102 if (opts->allow_rerere_auto)
3103 res |= git_config_set_in_file_gently(opts_file,
3104 "options.allow-rerere-auto",
3105 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3106 "true" : "false");
3108 if (opts->explicit_cleanup)
3109 res |= git_config_set_in_file_gently(opts_file,
3110 "options.default-msg-cleanup",
3111 describe_cleanup_mode(opts->default_msg_cleanup));
3112 return res;
3115 static int make_patch(struct repository *r,
3116 struct commit *commit,
3117 struct replay_opts *opts)
3119 struct strbuf buf = STRBUF_INIT;
3120 struct rev_info log_tree_opt;
3121 const char *subject;
3122 char hex[GIT_MAX_HEXSZ + 1];
3123 int res = 0;
3125 oid_to_hex_r(hex, &commit->object.oid);
3126 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3127 return -1;
3128 res |= write_rebase_head(&commit->object.oid);
3130 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3131 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3132 repo_init_revisions(r, &log_tree_opt, NULL);
3133 log_tree_opt.abbrev = 0;
3134 log_tree_opt.diff = 1;
3135 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3136 log_tree_opt.disable_stdin = 1;
3137 log_tree_opt.no_commit_id = 1;
3138 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3139 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3140 if (!log_tree_opt.diffopt.file)
3141 res |= error_errno(_("could not open '%s'"), buf.buf);
3142 else {
3143 res |= log_tree_commit(&log_tree_opt, commit);
3144 fclose(log_tree_opt.diffopt.file);
3146 strbuf_reset(&buf);
3148 strbuf_addf(&buf, "%s/message", get_dir(opts));
3149 if (!file_exists(buf.buf)) {
3150 const char *encoding = get_commit_output_encoding();
3151 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3152 find_commit_subject(commit_buffer, &subject);
3153 res |= write_message(subject, strlen(subject), buf.buf, 1);
3154 unuse_commit_buffer(commit, commit_buffer);
3156 strbuf_release(&buf);
3158 return res;
3161 static int intend_to_amend(void)
3163 struct object_id head;
3164 char *p;
3166 if (get_oid("HEAD", &head))
3167 return error(_("cannot read HEAD"));
3169 p = oid_to_hex(&head);
3170 return write_message(p, strlen(p), rebase_path_amend(), 1);
3173 static int error_with_patch(struct repository *r,
3174 struct commit *commit,
3175 const char *subject, int subject_len,
3176 struct replay_opts *opts,
3177 int exit_code, int to_amend)
3179 if (commit) {
3180 if (make_patch(r, commit, opts))
3181 return -1;
3182 } else if (copy_file(rebase_path_message(),
3183 git_path_merge_msg(r), 0666))
3184 return error(_("unable to copy '%s' to '%s'"),
3185 git_path_merge_msg(r), rebase_path_message());
3187 if (to_amend) {
3188 if (intend_to_amend())
3189 return -1;
3191 fprintf(stderr,
3192 _("You can amend the commit now, with\n"
3193 "\n"
3194 " git commit --amend %s\n"
3195 "\n"
3196 "Once you are satisfied with your changes, run\n"
3197 "\n"
3198 " git rebase --continue\n"),
3199 gpg_sign_opt_quoted(opts));
3200 } else if (exit_code) {
3201 if (commit)
3202 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3203 short_commit_name(commit), subject_len, subject);
3204 else
3206 * We don't have the hash of the parent so
3207 * just print the line from the todo file.
3209 fprintf_ln(stderr, _("Could not merge %.*s"),
3210 subject_len, subject);
3213 return exit_code;
3216 static int error_failed_squash(struct repository *r,
3217 struct commit *commit,
3218 struct replay_opts *opts,
3219 int subject_len,
3220 const char *subject)
3222 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3223 return error(_("could not copy '%s' to '%s'"),
3224 rebase_path_squash_msg(), rebase_path_message());
3225 unlink(git_path_merge_msg(r));
3226 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3227 return error(_("could not copy '%s' to '%s'"),
3228 rebase_path_message(),
3229 git_path_merge_msg(r));
3230 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3233 static int do_exec(struct repository *r, const char *command_line)
3235 struct strvec child_env = STRVEC_INIT;
3236 const char *child_argv[] = { NULL, NULL };
3237 int dirty, status;
3239 fprintf(stderr, _("Executing: %s\n"), command_line);
3240 child_argv[0] = command_line;
3241 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3242 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3243 absolute_path(get_git_work_tree()));
3244 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3245 child_env.v);
3247 /* force re-reading of the cache */
3248 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3249 return error(_("could not read index"));
3251 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3253 if (status) {
3254 warning(_("execution failed: %s\n%s"
3255 "You can fix the problem, and then run\n"
3256 "\n"
3257 " git rebase --continue\n"
3258 "\n"),
3259 command_line,
3260 dirty ? N_("and made changes to the index and/or the "
3261 "working tree\n") : "");
3262 if (status == 127)
3263 /* command not found */
3264 status = 1;
3265 } else if (dirty) {
3266 warning(_("execution succeeded: %s\nbut "
3267 "left changes to the index and/or the working tree\n"
3268 "Commit or stash your changes, and then run\n"
3269 "\n"
3270 " git rebase --continue\n"
3271 "\n"), command_line);
3272 status = 1;
3275 strvec_clear(&child_env);
3277 return status;
3280 static int safe_append(const char *filename, const char *fmt, ...)
3282 va_list ap;
3283 struct lock_file lock = LOCK_INIT;
3284 int fd = hold_lock_file_for_update(&lock, filename,
3285 LOCK_REPORT_ON_ERROR);
3286 struct strbuf buf = STRBUF_INIT;
3288 if (fd < 0)
3289 return -1;
3291 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3292 error_errno(_("could not read '%s'"), filename);
3293 rollback_lock_file(&lock);
3294 return -1;
3296 strbuf_complete(&buf, '\n');
3297 va_start(ap, fmt);
3298 strbuf_vaddf(&buf, fmt, ap);
3299 va_end(ap);
3301 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3302 error_errno(_("could not write to '%s'"), filename);
3303 strbuf_release(&buf);
3304 rollback_lock_file(&lock);
3305 return -1;
3307 if (commit_lock_file(&lock) < 0) {
3308 strbuf_release(&buf);
3309 rollback_lock_file(&lock);
3310 return error(_("failed to finalize '%s'"), filename);
3313 strbuf_release(&buf);
3314 return 0;
3317 static int do_label(struct repository *r, const char *name, int len)
3319 struct ref_store *refs = get_main_ref_store(r);
3320 struct ref_transaction *transaction;
3321 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3322 struct strbuf msg = STRBUF_INIT;
3323 int ret = 0;
3324 struct object_id head_oid;
3326 if (len == 1 && *name == '#')
3327 return error(_("illegal label name: '%.*s'"), len, name);
3329 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3330 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3332 transaction = ref_store_transaction_begin(refs, &err);
3333 if (!transaction) {
3334 error("%s", err.buf);
3335 ret = -1;
3336 } else if (get_oid("HEAD", &head_oid)) {
3337 error(_("could not read HEAD"));
3338 ret = -1;
3339 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3340 NULL, 0, msg.buf, &err) < 0 ||
3341 ref_transaction_commit(transaction, &err)) {
3342 error("%s", err.buf);
3343 ret = -1;
3345 ref_transaction_free(transaction);
3346 strbuf_release(&err);
3347 strbuf_release(&msg);
3349 if (!ret)
3350 ret = safe_append(rebase_path_refs_to_delete(),
3351 "%s\n", ref_name.buf);
3352 strbuf_release(&ref_name);
3354 return ret;
3357 static const char *reflog_message(struct replay_opts *opts,
3358 const char *sub_action, const char *fmt, ...);
3360 static int do_reset(struct repository *r,
3361 const char *name, int len,
3362 struct replay_opts *opts)
3364 struct strbuf ref_name = STRBUF_INIT;
3365 struct object_id oid;
3366 struct lock_file lock = LOCK_INIT;
3367 struct tree_desc desc;
3368 struct tree *tree;
3369 struct unpack_trees_options unpack_tree_opts;
3370 int ret = 0;
3372 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3373 return -1;
3375 if (len == 10 && !strncmp("[new root]", name, len)) {
3376 if (!opts->have_squash_onto) {
3377 const char *hex;
3378 if (commit_tree("", 0, the_hash_algo->empty_tree,
3379 NULL, &opts->squash_onto,
3380 NULL, NULL))
3381 return error(_("writing fake root commit"));
3382 opts->have_squash_onto = 1;
3383 hex = oid_to_hex(&opts->squash_onto);
3384 if (write_message(hex, strlen(hex),
3385 rebase_path_squash_onto(), 0))
3386 return error(_("writing squash-onto"));
3388 oidcpy(&oid, &opts->squash_onto);
3389 } else {
3390 int i;
3392 /* Determine the length of the label */
3393 for (i = 0; i < len; i++)
3394 if (isspace(name[i]))
3395 break;
3396 len = i;
3398 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3399 if (get_oid(ref_name.buf, &oid) &&
3400 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3401 error(_("could not read '%s'"), ref_name.buf);
3402 rollback_lock_file(&lock);
3403 strbuf_release(&ref_name);
3404 return -1;
3408 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3409 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3410 unpack_tree_opts.head_idx = 1;
3411 unpack_tree_opts.src_index = r->index;
3412 unpack_tree_opts.dst_index = r->index;
3413 unpack_tree_opts.fn = oneway_merge;
3414 unpack_tree_opts.merge = 1;
3415 unpack_tree_opts.update = 1;
3416 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3418 if (repo_read_index_unmerged(r)) {
3419 rollback_lock_file(&lock);
3420 strbuf_release(&ref_name);
3421 return error_resolve_conflict(_(action_name(opts)));
3424 if (!fill_tree_descriptor(r, &desc, &oid)) {
3425 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3426 rollback_lock_file(&lock);
3427 free((void *)desc.buffer);
3428 strbuf_release(&ref_name);
3429 return -1;
3432 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3433 rollback_lock_file(&lock);
3434 free((void *)desc.buffer);
3435 strbuf_release(&ref_name);
3436 return -1;
3439 tree = parse_tree_indirect(&oid);
3440 prime_cache_tree(r, r->index, tree);
3442 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3443 ret = error(_("could not write index"));
3444 free((void *)desc.buffer);
3446 if (!ret)
3447 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3448 len, name), "HEAD", &oid,
3449 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3451 strbuf_release(&ref_name);
3452 return ret;
3455 static struct commit *lookup_label(const char *label, int len,
3456 struct strbuf *buf)
3458 struct commit *commit;
3460 strbuf_reset(buf);
3461 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3462 commit = lookup_commit_reference_by_name(buf->buf);
3463 if (!commit) {
3464 /* fall back to non-rewritten ref or commit */
3465 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3466 commit = lookup_commit_reference_by_name(buf->buf);
3469 if (!commit)
3470 error(_("could not resolve '%s'"), buf->buf);
3472 return commit;
3475 static int do_merge(struct repository *r,
3476 struct commit *commit,
3477 const char *arg, int arg_len,
3478 int flags, struct replay_opts *opts)
3480 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3481 EDIT_MSG | VERIFY_MSG : 0;
3482 struct strbuf ref_name = STRBUF_INIT;
3483 struct commit *head_commit, *merge_commit, *i;
3484 struct commit_list *bases, *j, *reversed = NULL;
3485 struct commit_list *to_merge = NULL, **tail = &to_merge;
3486 const char *strategy = !opts->xopts_nr &&
3487 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3488 NULL : opts->strategy;
3489 struct merge_options o;
3490 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3491 static struct lock_file lock;
3492 const char *p;
3494 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3495 ret = -1;
3496 goto leave_merge;
3499 head_commit = lookup_commit_reference_by_name("HEAD");
3500 if (!head_commit) {
3501 ret = error(_("cannot merge without a current revision"));
3502 goto leave_merge;
3506 * For octopus merges, the arg starts with the list of revisions to be
3507 * merged. The list is optionally followed by '#' and the oneline.
3509 merge_arg_len = oneline_offset = arg_len;
3510 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3511 if (!*p)
3512 break;
3513 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3514 p += 1 + strspn(p + 1, " \t\n");
3515 oneline_offset = p - arg;
3516 break;
3518 k = strcspn(p, " \t\n");
3519 if (!k)
3520 continue;
3521 merge_commit = lookup_label(p, k, &ref_name);
3522 if (!merge_commit) {
3523 ret = error(_("unable to parse '%.*s'"), k, p);
3524 goto leave_merge;
3526 tail = &commit_list_insert(merge_commit, tail)->next;
3527 p += k;
3528 merge_arg_len = p - arg;
3531 if (!to_merge) {
3532 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3533 goto leave_merge;
3536 if (opts->have_squash_onto &&
3537 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3539 * When the user tells us to "merge" something into a
3540 * "[new root]", let's simply fast-forward to the merge head.
3542 rollback_lock_file(&lock);
3543 if (to_merge->next)
3544 ret = error(_("octopus merge cannot be executed on "
3545 "top of a [new root]"));
3546 else
3547 ret = fast_forward_to(r, &to_merge->item->object.oid,
3548 &head_commit->object.oid, 0,
3549 opts);
3550 goto leave_merge;
3553 if (commit) {
3554 const char *encoding = get_commit_output_encoding();
3555 const char *message = logmsg_reencode(commit, NULL, encoding);
3556 const char *body;
3557 int len;
3559 if (!message) {
3560 ret = error(_("could not get commit message of '%s'"),
3561 oid_to_hex(&commit->object.oid));
3562 goto leave_merge;
3564 write_author_script(message);
3565 find_commit_subject(message, &body);
3566 len = strlen(body);
3567 ret = write_message(body, len, git_path_merge_msg(r), 0);
3568 unuse_commit_buffer(commit, message);
3569 if (ret) {
3570 error_errno(_("could not write '%s'"),
3571 git_path_merge_msg(r));
3572 goto leave_merge;
3574 } else {
3575 struct strbuf buf = STRBUF_INIT;
3576 int len;
3578 strbuf_addf(&buf, "author %s", git_author_info(0));
3579 write_author_script(buf.buf);
3580 strbuf_reset(&buf);
3582 if (oneline_offset < arg_len) {
3583 p = arg + oneline_offset;
3584 len = arg_len - oneline_offset;
3585 } else {
3586 strbuf_addf(&buf, "Merge %s '%.*s'",
3587 to_merge->next ? "branches" : "branch",
3588 merge_arg_len, arg);
3589 p = buf.buf;
3590 len = buf.len;
3593 ret = write_message(p, len, git_path_merge_msg(r), 0);
3594 strbuf_release(&buf);
3595 if (ret) {
3596 error_errno(_("could not write '%s'"),
3597 git_path_merge_msg(r));
3598 goto leave_merge;
3603 * If HEAD is not identical to the first parent of the original merge
3604 * commit, we cannot fast-forward.
3606 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3607 oideq(&commit->parents->item->object.oid,
3608 &head_commit->object.oid);
3611 * If any merge head is different from the original one, we cannot
3612 * fast-forward.
3614 if (can_fast_forward) {
3615 struct commit_list *p = commit->parents->next;
3617 for (j = to_merge; j && p; j = j->next, p = p->next)
3618 if (!oideq(&j->item->object.oid,
3619 &p->item->object.oid)) {
3620 can_fast_forward = 0;
3621 break;
3624 * If the number of merge heads differs from the original merge
3625 * commit, we cannot fast-forward.
3627 if (j || p)
3628 can_fast_forward = 0;
3631 if (can_fast_forward) {
3632 rollback_lock_file(&lock);
3633 ret = fast_forward_to(r, &commit->object.oid,
3634 &head_commit->object.oid, 0, opts);
3635 if (flags & TODO_EDIT_MERGE_MSG) {
3636 run_commit_flags |= AMEND_MSG;
3637 goto fast_forward_edit;
3639 goto leave_merge;
3642 if (strategy || to_merge->next) {
3643 /* Octopus merge */
3644 struct child_process cmd = CHILD_PROCESS_INIT;
3646 if (read_env_script(&cmd.env_array)) {
3647 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3649 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3650 goto leave_merge;
3653 if (opts->committer_date_is_author_date)
3654 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3655 opts->ignore_date ?
3656 "" :
3657 author_date_from_env_array(&cmd.env_array));
3658 if (opts->ignore_date)
3659 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3661 cmd.git_cmd = 1;
3662 strvec_push(&cmd.args, "merge");
3663 strvec_push(&cmd.args, "-s");
3664 if (!strategy)
3665 strvec_push(&cmd.args, "octopus");
3666 else {
3667 strvec_push(&cmd.args, strategy);
3668 for (k = 0; k < opts->xopts_nr; k++)
3669 strvec_pushf(&cmd.args,
3670 "-X%s", opts->xopts[k]);
3672 strvec_push(&cmd.args, "--no-edit");
3673 strvec_push(&cmd.args, "--no-ff");
3674 strvec_push(&cmd.args, "--no-log");
3675 strvec_push(&cmd.args, "--no-stat");
3676 strvec_push(&cmd.args, "-F");
3677 strvec_push(&cmd.args, git_path_merge_msg(r));
3678 if (opts->gpg_sign)
3679 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3680 else
3681 strvec_push(&cmd.args, "--no-gpg-sign");
3683 /* Add the tips to be merged */
3684 for (j = to_merge; j; j = j->next)
3685 strvec_push(&cmd.args,
3686 oid_to_hex(&j->item->object.oid));
3688 strbuf_release(&ref_name);
3689 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3690 NULL, 0);
3691 rollback_lock_file(&lock);
3693 ret = run_command(&cmd);
3695 /* force re-reading of the cache */
3696 if (!ret && (discard_index(r->index) < 0 ||
3697 repo_read_index(r) < 0))
3698 ret = error(_("could not read index"));
3699 goto leave_merge;
3702 merge_commit = to_merge->item;
3703 bases = get_merge_bases(head_commit, merge_commit);
3704 if (bases && oideq(&merge_commit->object.oid,
3705 &bases->item->object.oid)) {
3706 ret = 0;
3707 /* skip merging an ancestor of HEAD */
3708 goto leave_merge;
3711 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3712 git_path_merge_head(r), 0);
3713 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3715 for (j = bases; j; j = j->next)
3716 commit_list_insert(j->item, &reversed);
3717 free_commit_list(bases);
3719 repo_read_index(r);
3720 init_merge_options(&o, r);
3721 o.branch1 = "HEAD";
3722 o.branch2 = ref_name.buf;
3723 o.buffer_output = 2;
3725 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3726 if (ret <= 0)
3727 fputs(o.obuf.buf, stdout);
3728 strbuf_release(&o.obuf);
3729 if (ret < 0) {
3730 error(_("could not even attempt to merge '%.*s'"),
3731 merge_arg_len, arg);
3732 goto leave_merge;
3735 * The return value of merge_recursive() is 1 on clean, and 0 on
3736 * unclean merge.
3738 * Let's reverse that, so that do_merge() returns 0 upon success and
3739 * 1 upon failed merge (keeping the return value -1 for the cases where
3740 * we will want to reschedule the `merge` command).
3742 ret = !ret;
3744 if (r->index->cache_changed &&
3745 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3746 ret = error(_("merge: Unable to write new index file"));
3747 goto leave_merge;
3750 rollback_lock_file(&lock);
3751 if (ret)
3752 repo_rerere(r, opts->allow_rerere_auto);
3753 else
3755 * In case of problems, we now want to return a positive
3756 * value (a negative one would indicate that the `merge`
3757 * command needs to be rescheduled).
3759 fast_forward_edit:
3760 ret = !!run_git_commit(git_path_merge_msg(r), opts,
3761 run_commit_flags);
3763 leave_merge:
3764 strbuf_release(&ref_name);
3765 rollback_lock_file(&lock);
3766 free_commit_list(to_merge);
3767 return ret;
3770 static int is_final_fixup(struct todo_list *todo_list)
3772 int i = todo_list->current;
3774 if (!is_fixup(todo_list->items[i].command))
3775 return 0;
3777 while (++i < todo_list->nr)
3778 if (is_fixup(todo_list->items[i].command))
3779 return 0;
3780 else if (!is_noop(todo_list->items[i].command))
3781 break;
3782 return 1;
3785 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3787 int i;
3789 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3790 if (!is_noop(todo_list->items[i].command))
3791 return todo_list->items[i].command;
3793 return -1;
3796 void create_autostash(struct repository *r, const char *path,
3797 const char *default_reflog_action)
3799 struct strbuf buf = STRBUF_INIT;
3800 struct lock_file lock_file = LOCK_INIT;
3801 int fd;
3803 fd = repo_hold_locked_index(r, &lock_file, 0);
3804 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3805 if (0 <= fd)
3806 repo_update_index_if_able(r, &lock_file);
3807 rollback_lock_file(&lock_file);
3809 if (has_unstaged_changes(r, 1) ||
3810 has_uncommitted_changes(r, 1)) {
3811 struct child_process stash = CHILD_PROCESS_INIT;
3812 struct object_id oid;
3814 strvec_pushl(&stash.args,
3815 "stash", "create", "autostash", NULL);
3816 stash.git_cmd = 1;
3817 stash.no_stdin = 1;
3818 strbuf_reset(&buf);
3819 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3820 die(_("Cannot autostash"));
3821 strbuf_trim_trailing_newline(&buf);
3822 if (get_oid(buf.buf, &oid))
3823 die(_("Unexpected stash response: '%s'"),
3824 buf.buf);
3825 strbuf_reset(&buf);
3826 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3828 if (safe_create_leading_directories_const(path))
3829 die(_("Could not create directory for '%s'"),
3830 path);
3831 write_file(path, "%s", oid_to_hex(&oid));
3832 printf(_("Created autostash: %s\n"), buf.buf);
3833 if (reset_head(r, NULL, "reset --hard",
3834 NULL, RESET_HEAD_HARD, NULL, NULL,
3835 default_reflog_action) < 0)
3836 die(_("could not reset --hard"));
3838 if (discard_index(r->index) < 0 ||
3839 repo_read_index(r) < 0)
3840 die(_("could not read index"));
3842 strbuf_release(&buf);
3845 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
3847 struct child_process child = CHILD_PROCESS_INIT;
3848 int ret = 0;
3850 if (attempt_apply) {
3851 child.git_cmd = 1;
3852 child.no_stdout = 1;
3853 child.no_stderr = 1;
3854 strvec_push(&child.args, "stash");
3855 strvec_push(&child.args, "apply");
3856 strvec_push(&child.args, stash_oid);
3857 ret = run_command(&child);
3860 if (attempt_apply && !ret)
3861 fprintf(stderr, _("Applied autostash.\n"));
3862 else {
3863 struct child_process store = CHILD_PROCESS_INIT;
3865 store.git_cmd = 1;
3866 strvec_push(&store.args, "stash");
3867 strvec_push(&store.args, "store");
3868 strvec_push(&store.args, "-m");
3869 strvec_push(&store.args, "autostash");
3870 strvec_push(&store.args, "-q");
3871 strvec_push(&store.args, stash_oid);
3872 if (run_command(&store))
3873 ret = error(_("cannot store %s"), stash_oid);
3874 else
3875 fprintf(stderr,
3876 _("%s\n"
3877 "Your changes are safe in the stash.\n"
3878 "You can run \"git stash pop\" or"
3879 " \"git stash drop\" at any time.\n"),
3880 attempt_apply ?
3881 _("Applying autostash resulted in conflicts.") :
3882 _("Autostash exists; creating a new stash entry."));
3885 return ret;
3888 static int apply_save_autostash(const char *path, int attempt_apply)
3890 struct strbuf stash_oid = STRBUF_INIT;
3891 int ret = 0;
3893 if (!read_oneliner(&stash_oid, path,
3894 READ_ONELINER_SKIP_IF_EMPTY)) {
3895 strbuf_release(&stash_oid);
3896 return 0;
3898 strbuf_trim(&stash_oid);
3900 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
3902 unlink(path);
3903 strbuf_release(&stash_oid);
3904 return ret;
3907 int save_autostash(const char *path)
3909 return apply_save_autostash(path, 0);
3912 int apply_autostash(const char *path)
3914 return apply_save_autostash(path, 1);
3917 int apply_autostash_oid(const char *stash_oid)
3919 return apply_save_autostash_oid(stash_oid, 1);
3922 static const char *reflog_message(struct replay_opts *opts,
3923 const char *sub_action, const char *fmt, ...)
3925 va_list ap;
3926 static struct strbuf buf = STRBUF_INIT;
3927 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3929 va_start(ap, fmt);
3930 strbuf_reset(&buf);
3931 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3932 if (sub_action)
3933 strbuf_addf(&buf, " (%s)", sub_action);
3934 if (fmt) {
3935 strbuf_addstr(&buf, ": ");
3936 strbuf_vaddf(&buf, fmt, ap);
3938 va_end(ap);
3940 return buf.buf;
3943 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3944 const char *commit, const char *action)
3946 struct child_process cmd = CHILD_PROCESS_INIT;
3947 int ret;
3949 cmd.git_cmd = 1;
3951 strvec_push(&cmd.args, "checkout");
3952 strvec_push(&cmd.args, commit);
3953 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3955 if (opts->verbose)
3956 ret = run_command(&cmd);
3957 else
3958 ret = run_command_silent_on_success(&cmd);
3960 if (!ret)
3961 discard_index(r->index);
3963 return ret;
3966 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3967 const char *onto_name, const struct object_id *onto,
3968 const struct object_id *orig_head)
3970 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3972 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3973 apply_autostash(rebase_path_autostash());
3974 sequencer_remove_state(opts);
3975 return error(_("could not detach HEAD"));
3978 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3981 static int stopped_at_head(struct repository *r)
3983 struct object_id head;
3984 struct commit *commit;
3985 struct commit_message message;
3987 if (get_oid("HEAD", &head) ||
3988 !(commit = lookup_commit(r, &head)) ||
3989 parse_commit(commit) || get_message(commit, &message))
3990 fprintf(stderr, _("Stopped at HEAD\n"));
3991 else {
3992 fprintf(stderr, _("Stopped at %s\n"), message.label);
3993 free_message(commit, &message);
3995 return 0;
3999 static const char rescheduled_advice[] =
4000 N_("Could not execute the todo command\n"
4001 "\n"
4002 " %.*s"
4003 "\n"
4004 "It has been rescheduled; To edit the command before continuing, please\n"
4005 "edit the todo list first:\n"
4006 "\n"
4007 " git rebase --edit-todo\n"
4008 " git rebase --continue\n");
4010 static int pick_commits(struct repository *r,
4011 struct todo_list *todo_list,
4012 struct replay_opts *opts)
4014 int res = 0, reschedule = 0;
4015 char *prev_reflog_action;
4017 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4018 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4019 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4020 if (opts->allow_ff)
4021 assert(!(opts->signoff || opts->no_commit ||
4022 opts->record_origin || opts->edit ||
4023 opts->committer_date_is_author_date ||
4024 opts->ignore_date));
4025 if (read_and_refresh_cache(r, opts))
4026 return -1;
4028 while (todo_list->current < todo_list->nr) {
4029 struct todo_item *item = todo_list->items + todo_list->current;
4030 const char *arg = todo_item_get_arg(todo_list, item);
4031 int check_todo = 0;
4033 if (save_todo(todo_list, opts))
4034 return -1;
4035 if (is_rebase_i(opts)) {
4036 if (item->command != TODO_COMMENT) {
4037 FILE *f = fopen(rebase_path_msgnum(), "w");
4039 todo_list->done_nr++;
4041 if (f) {
4042 fprintf(f, "%d\n", todo_list->done_nr);
4043 fclose(f);
4045 if (!opts->quiet)
4046 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4047 todo_list->done_nr,
4048 todo_list->total_nr,
4049 opts->verbose ? "\n" : "\r");
4051 unlink(rebase_path_message());
4052 unlink(rebase_path_author_script());
4053 unlink(rebase_path_stopped_sha());
4054 unlink(rebase_path_amend());
4055 unlink(git_path_merge_head(r));
4056 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4058 if (item->command == TODO_BREAK) {
4059 if (!opts->verbose)
4060 term_clear_line();
4061 return stopped_at_head(r);
4064 if (item->command <= TODO_SQUASH) {
4065 if (is_rebase_i(opts))
4066 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4067 command_to_string(item->command), NULL),
4069 res = do_pick_commit(r, item->command, item->commit,
4070 opts, is_final_fixup(todo_list),
4071 &check_todo);
4072 if (is_rebase_i(opts))
4073 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4074 if (is_rebase_i(opts) && res < 0) {
4075 /* Reschedule */
4076 advise(_(rescheduled_advice),
4077 get_item_line_length(todo_list,
4078 todo_list->current),
4079 get_item_line(todo_list,
4080 todo_list->current));
4081 todo_list->current--;
4082 if (save_todo(todo_list, opts))
4083 return -1;
4085 if (item->command == TODO_EDIT) {
4086 struct commit *commit = item->commit;
4087 if (!res) {
4088 if (!opts->verbose)
4089 term_clear_line();
4090 fprintf(stderr,
4091 _("Stopped at %s... %.*s\n"),
4092 short_commit_name(commit),
4093 item->arg_len, arg);
4095 return error_with_patch(r, commit,
4096 arg, item->arg_len, opts, res, !res);
4098 if (is_rebase_i(opts) && !res)
4099 record_in_rewritten(&item->commit->object.oid,
4100 peek_command(todo_list, 1));
4101 if (res && is_fixup(item->command)) {
4102 if (res == 1)
4103 intend_to_amend();
4104 return error_failed_squash(r, item->commit, opts,
4105 item->arg_len, arg);
4106 } else if (res && is_rebase_i(opts) && item->commit) {
4107 int to_amend = 0;
4108 struct object_id oid;
4111 * If we are rewording and have either
4112 * fast-forwarded already, or are about to
4113 * create a new root commit, we want to amend,
4114 * otherwise we do not.
4116 if (item->command == TODO_REWORD &&
4117 !get_oid("HEAD", &oid) &&
4118 (oideq(&item->commit->object.oid, &oid) ||
4119 (opts->have_squash_onto &&
4120 oideq(&opts->squash_onto, &oid))))
4121 to_amend = 1;
4123 return res | error_with_patch(r, item->commit,
4124 arg, item->arg_len, opts,
4125 res, to_amend);
4127 } else if (item->command == TODO_EXEC) {
4128 char *end_of_arg = (char *)(arg + item->arg_len);
4129 int saved = *end_of_arg;
4131 if (!opts->verbose)
4132 term_clear_line();
4133 *end_of_arg = '\0';
4134 res = do_exec(r, arg);
4135 *end_of_arg = saved;
4137 if (res) {
4138 if (opts->reschedule_failed_exec)
4139 reschedule = 1;
4141 check_todo = 1;
4142 } else if (item->command == TODO_LABEL) {
4143 if ((res = do_label(r, arg, item->arg_len)))
4144 reschedule = 1;
4145 } else if (item->command == TODO_RESET) {
4146 if ((res = do_reset(r, arg, item->arg_len, opts)))
4147 reschedule = 1;
4148 } else if (item->command == TODO_MERGE) {
4149 if ((res = do_merge(r, item->commit,
4150 arg, item->arg_len,
4151 item->flags, opts)) < 0)
4152 reschedule = 1;
4153 else if (item->commit)
4154 record_in_rewritten(&item->commit->object.oid,
4155 peek_command(todo_list, 1));
4156 if (res > 0)
4157 /* failed with merge conflicts */
4158 return error_with_patch(r, item->commit,
4159 arg, item->arg_len,
4160 opts, res, 0);
4161 } else if (!is_noop(item->command))
4162 return error(_("unknown command %d"), item->command);
4164 if (reschedule) {
4165 advise(_(rescheduled_advice),
4166 get_item_line_length(todo_list,
4167 todo_list->current),
4168 get_item_line(todo_list, todo_list->current));
4169 todo_list->current--;
4170 if (save_todo(todo_list, opts))
4171 return -1;
4172 if (item->commit)
4173 return error_with_patch(r,
4174 item->commit,
4175 arg, item->arg_len,
4176 opts, res, 0);
4177 } else if (is_rebase_i(opts) && check_todo && !res) {
4178 struct stat st;
4180 if (stat(get_todo_path(opts), &st)) {
4181 res = error_errno(_("could not stat '%s'"),
4182 get_todo_path(opts));
4183 } else if (match_stat_data(&todo_list->stat, &st)) {
4184 /* Reread the todo file if it has changed. */
4185 todo_list_release(todo_list);
4186 if (read_populate_todo(r, todo_list, opts))
4187 res = -1; /* message was printed */
4188 /* `current` will be incremented below */
4189 todo_list->current = -1;
4193 todo_list->current++;
4194 if (res)
4195 return res;
4198 if (is_rebase_i(opts)) {
4199 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4200 struct stat st;
4202 /* Stopped in the middle, as planned? */
4203 if (todo_list->current < todo_list->nr)
4204 return 0;
4206 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4207 starts_with(head_ref.buf, "refs/")) {
4208 const char *msg;
4209 struct object_id head, orig;
4210 int res;
4212 if (get_oid("HEAD", &head)) {
4213 res = error(_("cannot read HEAD"));
4214 cleanup_head_ref:
4215 strbuf_release(&head_ref);
4216 strbuf_release(&buf);
4217 return res;
4219 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4220 get_oid_hex(buf.buf, &orig)) {
4221 res = error(_("could not read orig-head"));
4222 goto cleanup_head_ref;
4224 strbuf_reset(&buf);
4225 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4226 res = error(_("could not read 'onto'"));
4227 goto cleanup_head_ref;
4229 msg = reflog_message(opts, "finish", "%s onto %s",
4230 head_ref.buf, buf.buf);
4231 if (update_ref(msg, head_ref.buf, &head, &orig,
4232 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4233 res = error(_("could not update %s"),
4234 head_ref.buf);
4235 goto cleanup_head_ref;
4237 msg = reflog_message(opts, "finish", "returning to %s",
4238 head_ref.buf);
4239 if (create_symref("HEAD", head_ref.buf, msg)) {
4240 res = error(_("could not update HEAD to %s"),
4241 head_ref.buf);
4242 goto cleanup_head_ref;
4244 strbuf_reset(&buf);
4247 if (opts->verbose) {
4248 struct rev_info log_tree_opt;
4249 struct object_id orig, head;
4251 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4252 repo_init_revisions(r, &log_tree_opt, NULL);
4253 log_tree_opt.diff = 1;
4254 log_tree_opt.diffopt.output_format =
4255 DIFF_FORMAT_DIFFSTAT;
4256 log_tree_opt.disable_stdin = 1;
4258 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4259 !get_oid(buf.buf, &orig) &&
4260 !get_oid("HEAD", &head)) {
4261 diff_tree_oid(&orig, &head, "",
4262 &log_tree_opt.diffopt);
4263 log_tree_diff_flush(&log_tree_opt);
4266 flush_rewritten_pending();
4267 if (!stat(rebase_path_rewritten_list(), &st) &&
4268 st.st_size > 0) {
4269 struct child_process child = CHILD_PROCESS_INIT;
4270 const char *post_rewrite_hook =
4271 find_hook("post-rewrite");
4273 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4274 child.git_cmd = 1;
4275 strvec_push(&child.args, "notes");
4276 strvec_push(&child.args, "copy");
4277 strvec_push(&child.args, "--for-rewrite=rebase");
4278 /* we don't care if this copying failed */
4279 run_command(&child);
4281 if (post_rewrite_hook) {
4282 struct child_process hook = CHILD_PROCESS_INIT;
4284 hook.in = open(rebase_path_rewritten_list(),
4285 O_RDONLY);
4286 hook.stdout_to_stderr = 1;
4287 hook.trace2_hook_name = "post-rewrite";
4288 strvec_push(&hook.args, post_rewrite_hook);
4289 strvec_push(&hook.args, "rebase");
4290 /* we don't care if this hook failed */
4291 run_command(&hook);
4294 apply_autostash(rebase_path_autostash());
4296 if (!opts->quiet) {
4297 if (!opts->verbose)
4298 term_clear_line();
4299 fprintf(stderr,
4300 _("Successfully rebased and updated %s.\n"),
4301 head_ref.buf);
4304 strbuf_release(&buf);
4305 strbuf_release(&head_ref);
4309 * Sequence of picks finished successfully; cleanup by
4310 * removing the .git/sequencer directory
4312 return sequencer_remove_state(opts);
4315 static int continue_single_pick(struct repository *r)
4317 const char *argv[] = { "commit", NULL };
4319 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4320 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4321 return error(_("no cherry-pick or revert in progress"));
4322 return run_command_v_opt(argv, RUN_GIT_CMD);
4325 static int commit_staged_changes(struct repository *r,
4326 struct replay_opts *opts,
4327 struct todo_list *todo_list)
4329 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4330 unsigned int final_fixup = 0, is_clean;
4332 if (has_unstaged_changes(r, 1))
4333 return error(_("cannot rebase: You have unstaged changes."));
4335 is_clean = !has_uncommitted_changes(r, 0);
4337 if (file_exists(rebase_path_amend())) {
4338 struct strbuf rev = STRBUF_INIT;
4339 struct object_id head, to_amend;
4341 if (get_oid("HEAD", &head))
4342 return error(_("cannot amend non-existing commit"));
4343 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4344 return error(_("invalid file: '%s'"), rebase_path_amend());
4345 if (get_oid_hex(rev.buf, &to_amend))
4346 return error(_("invalid contents: '%s'"),
4347 rebase_path_amend());
4348 if (!is_clean && !oideq(&head, &to_amend))
4349 return error(_("\nYou have uncommitted changes in your "
4350 "working tree. Please, commit them\n"
4351 "first and then run 'git rebase "
4352 "--continue' again."));
4354 * When skipping a failed fixup/squash, we need to edit the
4355 * commit message, the current fixup list and count, and if it
4356 * was the last fixup/squash in the chain, we need to clean up
4357 * the commit message and if there was a squash, let the user
4358 * edit it.
4360 if (!is_clean || !opts->current_fixup_count)
4361 ; /* this is not the final fixup */
4362 else if (!oideq(&head, &to_amend) ||
4363 !file_exists(rebase_path_stopped_sha())) {
4364 /* was a final fixup or squash done manually? */
4365 if (!is_fixup(peek_command(todo_list, 0))) {
4366 unlink(rebase_path_fixup_msg());
4367 unlink(rebase_path_squash_msg());
4368 unlink(rebase_path_current_fixups());
4369 strbuf_reset(&opts->current_fixups);
4370 opts->current_fixup_count = 0;
4372 } else {
4373 /* we are in a fixup/squash chain */
4374 const char *p = opts->current_fixups.buf;
4375 int len = opts->current_fixups.len;
4377 opts->current_fixup_count--;
4378 if (!len)
4379 BUG("Incorrect current_fixups:\n%s", p);
4380 while (len && p[len - 1] != '\n')
4381 len--;
4382 strbuf_setlen(&opts->current_fixups, len);
4383 if (write_message(p, len, rebase_path_current_fixups(),
4384 0) < 0)
4385 return error(_("could not write file: '%s'"),
4386 rebase_path_current_fixups());
4389 * If a fixup/squash in a fixup/squash chain failed, the
4390 * commit message is already correct, no need to commit
4391 * it again.
4393 * Only if it is the final command in the fixup/squash
4394 * chain, and only if the chain is longer than a single
4395 * fixup/squash command (which was just skipped), do we
4396 * actually need to re-commit with a cleaned up commit
4397 * message.
4399 if (opts->current_fixup_count > 0 &&
4400 !is_fixup(peek_command(todo_list, 0))) {
4401 final_fixup = 1;
4403 * If there was not a single "squash" in the
4404 * chain, we only need to clean up the commit
4405 * message, no need to bother the user with
4406 * opening the commit message in the editor.
4408 if (!starts_with(p, "squash ") &&
4409 !strstr(p, "\nsquash "))
4410 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4411 } else if (is_fixup(peek_command(todo_list, 0))) {
4413 * We need to update the squash message to skip
4414 * the latest commit message.
4416 struct commit *commit;
4417 const char *path = rebase_path_squash_msg();
4418 const char *encoding = get_commit_output_encoding();
4420 if (parse_head(r, &commit) ||
4421 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4422 write_message(p, strlen(p), path, 0)) {
4423 unuse_commit_buffer(commit, p);
4424 return error(_("could not write file: "
4425 "'%s'"), path);
4427 unuse_commit_buffer(commit, p);
4431 strbuf_release(&rev);
4432 flags |= AMEND_MSG;
4435 if (is_clean) {
4436 if (refs_ref_exists(get_main_ref_store(r),
4437 "CHERRY_PICK_HEAD") &&
4438 refs_delete_ref(get_main_ref_store(r), "",
4439 "CHERRY_PICK_HEAD", NULL, 0))
4440 return error(_("could not remove CHERRY_PICK_HEAD"));
4441 if (!final_fixup)
4442 return 0;
4445 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4446 opts, flags))
4447 return error(_("could not commit staged changes."));
4448 unlink(rebase_path_amend());
4449 unlink(git_path_merge_head(r));
4450 if (final_fixup) {
4451 unlink(rebase_path_fixup_msg());
4452 unlink(rebase_path_squash_msg());
4454 if (opts->current_fixup_count > 0) {
4456 * Whether final fixup or not, we just cleaned up the commit
4457 * message...
4459 unlink(rebase_path_current_fixups());
4460 strbuf_reset(&opts->current_fixups);
4461 opts->current_fixup_count = 0;
4463 return 0;
4466 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4468 struct todo_list todo_list = TODO_LIST_INIT;
4469 int res;
4471 if (read_and_refresh_cache(r, opts))
4472 return -1;
4474 if (read_populate_opts(opts))
4475 return -1;
4476 if (is_rebase_i(opts)) {
4477 if ((res = read_populate_todo(r, &todo_list, opts)))
4478 goto release_todo_list;
4480 if (file_exists(rebase_path_dropped())) {
4481 if ((res = todo_list_check_against_backup(r, &todo_list)))
4482 goto release_todo_list;
4484 unlink(rebase_path_dropped());
4487 if (commit_staged_changes(r, opts, &todo_list)) {
4488 res = -1;
4489 goto release_todo_list;
4491 } else if (!file_exists(get_todo_path(opts)))
4492 return continue_single_pick(r);
4493 else if ((res = read_populate_todo(r, &todo_list, opts)))
4494 goto release_todo_list;
4496 if (!is_rebase_i(opts)) {
4497 /* Verify that the conflict has been resolved */
4498 if (refs_ref_exists(get_main_ref_store(r),
4499 "CHERRY_PICK_HEAD") ||
4500 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4501 res = continue_single_pick(r);
4502 if (res)
4503 goto release_todo_list;
4505 if (index_differs_from(r, "HEAD", NULL, 0)) {
4506 res = error_dirty_index(r, opts);
4507 goto release_todo_list;
4509 todo_list.current++;
4510 } else if (file_exists(rebase_path_stopped_sha())) {
4511 struct strbuf buf = STRBUF_INIT;
4512 struct object_id oid;
4514 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4515 READ_ONELINER_SKIP_IF_EMPTY) &&
4516 !get_oid_hex(buf.buf, &oid))
4517 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4518 strbuf_release(&buf);
4521 res = pick_commits(r, &todo_list, opts);
4522 release_todo_list:
4523 todo_list_release(&todo_list);
4524 return res;
4527 static int single_pick(struct repository *r,
4528 struct commit *cmit,
4529 struct replay_opts *opts)
4531 int check_todo;
4533 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4534 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4535 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4536 &check_todo);
4539 int sequencer_pick_revisions(struct repository *r,
4540 struct replay_opts *opts)
4542 struct todo_list todo_list = TODO_LIST_INIT;
4543 struct object_id oid;
4544 int i, res;
4546 assert(opts->revs);
4547 if (read_and_refresh_cache(r, opts))
4548 return -1;
4550 for (i = 0; i < opts->revs->pending.nr; i++) {
4551 struct object_id oid;
4552 const char *name = opts->revs->pending.objects[i].name;
4554 /* This happens when using --stdin. */
4555 if (!strlen(name))
4556 continue;
4558 if (!get_oid(name, &oid)) {
4559 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4560 enum object_type type = oid_object_info(r,
4561 &oid,
4562 NULL);
4563 return error(_("%s: can't cherry-pick a %s"),
4564 name, type_name(type));
4566 } else
4567 return error(_("%s: bad revision"), name);
4571 * If we were called as "git cherry-pick <commit>", just
4572 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4573 * REVERT_HEAD, and don't touch the sequencer state.
4574 * This means it is possible to cherry-pick in the middle
4575 * of a cherry-pick sequence.
4577 if (opts->revs->cmdline.nr == 1 &&
4578 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4579 opts->revs->no_walk &&
4580 !opts->revs->cmdline.rev->flags) {
4581 struct commit *cmit;
4582 if (prepare_revision_walk(opts->revs))
4583 return error(_("revision walk setup failed"));
4584 cmit = get_revision(opts->revs);
4585 if (!cmit)
4586 return error(_("empty commit set passed"));
4587 if (get_revision(opts->revs))
4588 BUG("unexpected extra commit from walk");
4589 return single_pick(r, cmit, opts);
4593 * Start a new cherry-pick/ revert sequence; but
4594 * first, make sure that an existing one isn't in
4595 * progress
4598 if (walk_revs_populate_todo(&todo_list, opts) ||
4599 create_seq_dir(r) < 0)
4600 return -1;
4601 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4602 return error(_("can't revert as initial commit"));
4603 if (save_head(oid_to_hex(&oid)))
4604 return -1;
4605 if (save_opts(opts))
4606 return -1;
4607 update_abort_safety_file();
4608 res = pick_commits(r, &todo_list, opts);
4609 todo_list_release(&todo_list);
4610 return res;
4613 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4615 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4616 struct strbuf sob = STRBUF_INIT;
4617 int has_footer;
4619 strbuf_addstr(&sob, sign_off_header);
4620 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4621 strbuf_addch(&sob, '\n');
4623 if (!ignore_footer)
4624 strbuf_complete_line(msgbuf);
4627 * If the whole message buffer is equal to the sob, pretend that we
4628 * found a conforming footer with a matching sob
4630 if (msgbuf->len - ignore_footer == sob.len &&
4631 !strncmp(msgbuf->buf, sob.buf, sob.len))
4632 has_footer = 3;
4633 else
4634 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4636 if (!has_footer) {
4637 const char *append_newlines = NULL;
4638 size_t len = msgbuf->len - ignore_footer;
4640 if (!len) {
4642 * The buffer is completely empty. Leave foom for
4643 * the title and body to be filled in by the user.
4645 append_newlines = "\n\n";
4646 } else if (len == 1) {
4648 * Buffer contains a single newline. Add another
4649 * so that we leave room for the title and body.
4651 append_newlines = "\n";
4652 } else if (msgbuf->buf[len - 2] != '\n') {
4654 * Buffer ends with a single newline. Add another
4655 * so that there is an empty line between the message
4656 * body and the sob.
4658 append_newlines = "\n";
4659 } /* else, the buffer already ends with two newlines. */
4661 if (append_newlines)
4662 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4663 append_newlines, strlen(append_newlines));
4666 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4667 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4668 sob.buf, sob.len);
4670 strbuf_release(&sob);
4673 struct labels_entry {
4674 struct hashmap_entry entry;
4675 char label[FLEX_ARRAY];
4678 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4679 const struct hashmap_entry *entry_or_key, const void *key)
4681 const struct labels_entry *a, *b;
4683 a = container_of(eptr, const struct labels_entry, entry);
4684 b = container_of(entry_or_key, const struct labels_entry, entry);
4686 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4689 struct string_entry {
4690 struct oidmap_entry entry;
4691 char string[FLEX_ARRAY];
4694 struct label_state {
4695 struct oidmap commit2label;
4696 struct hashmap labels;
4697 struct strbuf buf;
4700 static const char *label_oid(struct object_id *oid, const char *label,
4701 struct label_state *state)
4703 struct labels_entry *labels_entry;
4704 struct string_entry *string_entry;
4705 struct object_id dummy;
4706 int i;
4708 string_entry = oidmap_get(&state->commit2label, oid);
4709 if (string_entry)
4710 return string_entry->string;
4713 * For "uninteresting" commits, i.e. commits that are not to be
4714 * rebased, and which can therefore not be labeled, we use a unique
4715 * abbreviation of the commit name. This is slightly more complicated
4716 * than calling find_unique_abbrev() because we also need to make
4717 * sure that the abbreviation does not conflict with any other
4718 * label.
4720 * We disallow "interesting" commits to be labeled by a string that
4721 * is a valid full-length hash, to ensure that we always can find an
4722 * abbreviation for any uninteresting commit's names that does not
4723 * clash with any other label.
4725 strbuf_reset(&state->buf);
4726 if (!label) {
4727 char *p;
4729 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4730 label = p = state->buf.buf;
4732 find_unique_abbrev_r(p, oid, default_abbrev);
4735 * We may need to extend the abbreviated hash so that there is
4736 * no conflicting label.
4738 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4739 size_t i = strlen(p) + 1;
4741 oid_to_hex_r(p, oid);
4742 for (; i < the_hash_algo->hexsz; i++) {
4743 char save = p[i];
4744 p[i] = '\0';
4745 if (!hashmap_get_from_hash(&state->labels,
4746 strihash(p), p))
4747 break;
4748 p[i] = save;
4751 } else {
4752 struct strbuf *buf = &state->buf;
4755 * Sanitize labels by replacing non-alpha-numeric characters
4756 * (including white-space ones) by dashes, as they might be
4757 * illegal in file names (and hence in ref names).
4759 * Note that we retain non-ASCII UTF-8 characters (identified
4760 * via the most significant bit). They should be all acceptable
4761 * in file names. We do not validate the UTF-8 here, that's not
4762 * the job of this function.
4764 for (; *label; label++)
4765 if ((*label & 0x80) || isalnum(*label))
4766 strbuf_addch(buf, *label);
4767 /* avoid leading dash and double-dashes */
4768 else if (buf->len && buf->buf[buf->len - 1] != '-')
4769 strbuf_addch(buf, '-');
4770 if (!buf->len) {
4771 strbuf_addstr(buf, "rev-");
4772 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4774 label = buf->buf;
4776 if ((buf->len == the_hash_algo->hexsz &&
4777 !get_oid_hex(label, &dummy)) ||
4778 (buf->len == 1 && *label == '#') ||
4779 hashmap_get_from_hash(&state->labels,
4780 strihash(label), label)) {
4782 * If the label already exists, or if the label is a
4783 * valid full OID, or the label is a '#' (which we use
4784 * as a separator between merge heads and oneline), we
4785 * append a dash and a number to make it unique.
4787 size_t len = buf->len;
4789 for (i = 2; ; i++) {
4790 strbuf_setlen(buf, len);
4791 strbuf_addf(buf, "-%d", i);
4792 if (!hashmap_get_from_hash(&state->labels,
4793 strihash(buf->buf),
4794 buf->buf))
4795 break;
4798 label = buf->buf;
4802 FLEX_ALLOC_STR(labels_entry, label, label);
4803 hashmap_entry_init(&labels_entry->entry, strihash(label));
4804 hashmap_add(&state->labels, &labels_entry->entry);
4806 FLEX_ALLOC_STR(string_entry, string, label);
4807 oidcpy(&string_entry->entry.oid, oid);
4808 oidmap_put(&state->commit2label, string_entry);
4810 return string_entry->string;
4813 static int make_script_with_merges(struct pretty_print_context *pp,
4814 struct rev_info *revs, struct strbuf *out,
4815 unsigned flags)
4817 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4818 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4819 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4820 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4821 struct strbuf label = STRBUF_INIT;
4822 struct commit_list *commits = NULL, **tail = &commits, *iter;
4823 struct commit_list *tips = NULL, **tips_tail = &tips;
4824 struct commit *commit;
4825 struct oidmap commit2todo = OIDMAP_INIT;
4826 struct string_entry *entry;
4827 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4828 shown = OIDSET_INIT;
4829 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4831 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4832 const char *cmd_pick = abbr ? "p" : "pick",
4833 *cmd_label = abbr ? "l" : "label",
4834 *cmd_reset = abbr ? "t" : "reset",
4835 *cmd_merge = abbr ? "m" : "merge";
4837 oidmap_init(&commit2todo, 0);
4838 oidmap_init(&state.commit2label, 0);
4839 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4840 strbuf_init(&state.buf, 32);
4842 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4843 struct labels_entry *onto_label_entry;
4844 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4845 FLEX_ALLOC_STR(entry, string, "onto");
4846 oidcpy(&entry->entry.oid, oid);
4847 oidmap_put(&state.commit2label, entry);
4849 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4850 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4851 hashmap_add(&state.labels, &onto_label_entry->entry);
4855 * First phase:
4856 * - get onelines for all commits
4857 * - gather all branch tips (i.e. 2nd or later parents of merges)
4858 * - label all branch tips
4860 while ((commit = get_revision(revs))) {
4861 struct commit_list *to_merge;
4862 const char *p1, *p2;
4863 struct object_id *oid;
4864 int is_empty;
4866 tail = &commit_list_insert(commit, tail)->next;
4867 oidset_insert(&interesting, &commit->object.oid);
4869 is_empty = is_original_commit_empty(commit);
4870 if (!is_empty && (commit->object.flags & PATCHSAME))
4871 continue;
4872 if (is_empty && !keep_empty)
4873 continue;
4875 strbuf_reset(&oneline);
4876 pretty_print_commit(pp, commit, &oneline);
4878 to_merge = commit->parents ? commit->parents->next : NULL;
4879 if (!to_merge) {
4880 /* non-merge commit: easy case */
4881 strbuf_reset(&buf);
4882 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4883 oid_to_hex(&commit->object.oid),
4884 oneline.buf);
4885 if (is_empty)
4886 strbuf_addf(&buf, " %c empty",
4887 comment_line_char);
4889 FLEX_ALLOC_STR(entry, string, buf.buf);
4890 oidcpy(&entry->entry.oid, &commit->object.oid);
4891 oidmap_put(&commit2todo, entry);
4893 continue;
4896 /* Create a label */
4897 strbuf_reset(&label);
4898 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4899 (p1 = strchr(p1, '\'')) &&
4900 (p2 = strchr(++p1, '\'')))
4901 strbuf_add(&label, p1, p2 - p1);
4902 else if (skip_prefix(oneline.buf, "Merge pull request ",
4903 &p1) &&
4904 (p1 = strstr(p1, " from ")))
4905 strbuf_addstr(&label, p1 + strlen(" from "));
4906 else
4907 strbuf_addbuf(&label, &oneline);
4909 strbuf_reset(&buf);
4910 strbuf_addf(&buf, "%s -C %s",
4911 cmd_merge, oid_to_hex(&commit->object.oid));
4913 /* label the tips of merged branches */
4914 for (; to_merge; to_merge = to_merge->next) {
4915 oid = &to_merge->item->object.oid;
4916 strbuf_addch(&buf, ' ');
4918 if (!oidset_contains(&interesting, oid)) {
4919 strbuf_addstr(&buf, label_oid(oid, NULL,
4920 &state));
4921 continue;
4924 tips_tail = &commit_list_insert(to_merge->item,
4925 tips_tail)->next;
4927 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4929 strbuf_addf(&buf, " # %s", oneline.buf);
4931 FLEX_ALLOC_STR(entry, string, buf.buf);
4932 oidcpy(&entry->entry.oid, &commit->object.oid);
4933 oidmap_put(&commit2todo, entry);
4937 * Second phase:
4938 * - label branch points
4939 * - add HEAD to the branch tips
4941 for (iter = commits; iter; iter = iter->next) {
4942 struct commit_list *parent = iter->item->parents;
4943 for (; parent; parent = parent->next) {
4944 struct object_id *oid = &parent->item->object.oid;
4945 if (!oidset_contains(&interesting, oid))
4946 continue;
4947 if (oidset_insert(&child_seen, oid))
4948 label_oid(oid, "branch-point", &state);
4951 /* Add HEAD as implicit "tip of branch" */
4952 if (!iter->next)
4953 tips_tail = &commit_list_insert(iter->item,
4954 tips_tail)->next;
4958 * Third phase: output the todo list. This is a bit tricky, as we
4959 * want to avoid jumping back and forth between revisions. To
4960 * accomplish that goal, we walk backwards from the branch tips,
4961 * gathering commits not yet shown, reversing the list on the fly,
4962 * then outputting that list (labeling revisions as needed).
4964 strbuf_addf(out, "%s onto\n", cmd_label);
4965 for (iter = tips; iter; iter = iter->next) {
4966 struct commit_list *list = NULL, *iter2;
4968 commit = iter->item;
4969 if (oidset_contains(&shown, &commit->object.oid))
4970 continue;
4971 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4973 if (entry)
4974 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4975 else
4976 strbuf_addch(out, '\n');
4978 while (oidset_contains(&interesting, &commit->object.oid) &&
4979 !oidset_contains(&shown, &commit->object.oid)) {
4980 commit_list_insert(commit, &list);
4981 if (!commit->parents) {
4982 commit = NULL;
4983 break;
4985 commit = commit->parents->item;
4988 if (!commit)
4989 strbuf_addf(out, "%s %s\n", cmd_reset,
4990 rebase_cousins || root_with_onto ?
4991 "onto" : "[new root]");
4992 else {
4993 const char *to = NULL;
4995 entry = oidmap_get(&state.commit2label,
4996 &commit->object.oid);
4997 if (entry)
4998 to = entry->string;
4999 else if (!rebase_cousins)
5000 to = label_oid(&commit->object.oid, NULL,
5001 &state);
5003 if (!to || !strcmp(to, "onto"))
5004 strbuf_addf(out, "%s onto\n", cmd_reset);
5005 else {
5006 strbuf_reset(&oneline);
5007 pretty_print_commit(pp, commit, &oneline);
5008 strbuf_addf(out, "%s %s # %s\n",
5009 cmd_reset, to, oneline.buf);
5013 for (iter2 = list; iter2; iter2 = iter2->next) {
5014 struct object_id *oid = &iter2->item->object.oid;
5015 entry = oidmap_get(&commit2todo, oid);
5016 /* only show if not already upstream */
5017 if (entry)
5018 strbuf_addf(out, "%s\n", entry->string);
5019 entry = oidmap_get(&state.commit2label, oid);
5020 if (entry)
5021 strbuf_addf(out, "%s %s\n",
5022 cmd_label, entry->string);
5023 oidset_insert(&shown, oid);
5026 free_commit_list(list);
5029 free_commit_list(commits);
5030 free_commit_list(tips);
5032 strbuf_release(&label);
5033 strbuf_release(&oneline);
5034 strbuf_release(&buf);
5036 oidmap_free(&commit2todo, 1);
5037 oidmap_free(&state.commit2label, 1);
5038 hashmap_free_entries(&state.labels, struct labels_entry, entry);
5039 strbuf_release(&state.buf);
5041 return 0;
5044 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5045 const char **argv, unsigned flags)
5047 char *format = NULL;
5048 struct pretty_print_context pp = {0};
5049 struct rev_info revs;
5050 struct commit *commit;
5051 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5052 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5053 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5054 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5056 repo_init_revisions(r, &revs, NULL);
5057 revs.verbose_header = 1;
5058 if (!rebase_merges)
5059 revs.max_parents = 1;
5060 revs.cherry_mark = !reapply_cherry_picks;
5061 revs.limited = 1;
5062 revs.reverse = 1;
5063 revs.right_only = 1;
5064 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5065 revs.topo_order = 1;
5067 revs.pretty_given = 1;
5068 git_config_get_string("rebase.instructionFormat", &format);
5069 if (!format || !*format) {
5070 free(format);
5071 format = xstrdup("%s");
5073 get_commit_format(format, &revs);
5074 free(format);
5075 pp.fmt = revs.commit_format;
5076 pp.output_encoding = get_log_output_encoding();
5078 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5079 return error(_("make_script: unhandled options"));
5081 if (prepare_revision_walk(&revs) < 0)
5082 return error(_("make_script: error preparing revisions"));
5084 if (rebase_merges)
5085 return make_script_with_merges(&pp, &revs, out, flags);
5087 while ((commit = get_revision(&revs))) {
5088 int is_empty = is_original_commit_empty(commit);
5090 if (!is_empty && (commit->object.flags & PATCHSAME))
5091 continue;
5092 if (is_empty && !keep_empty)
5093 continue;
5094 strbuf_addf(out, "%s %s ", insn,
5095 oid_to_hex(&commit->object.oid));
5096 pretty_print_commit(&pp, commit, out);
5097 if (is_empty)
5098 strbuf_addf(out, " %c empty", comment_line_char);
5099 strbuf_addch(out, '\n');
5101 return 0;
5105 * Add commands after pick and (series of) squash/fixup commands
5106 * in the todo list.
5108 void todo_list_add_exec_commands(struct todo_list *todo_list,
5109 struct string_list *commands)
5111 struct strbuf *buf = &todo_list->buf;
5112 size_t base_offset = buf->len;
5113 int i, insert, nr = 0, alloc = 0;
5114 struct todo_item *items = NULL, *base_items = NULL;
5116 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
5117 for (i = 0; i < commands->nr; i++) {
5118 size_t command_len = strlen(commands->items[i].string);
5120 strbuf_addstr(buf, commands->items[i].string);
5121 strbuf_addch(buf, '\n');
5123 base_items[i].command = TODO_EXEC;
5124 base_items[i].offset_in_buf = base_offset;
5125 base_items[i].arg_offset = base_offset + strlen("exec ");
5126 base_items[i].arg_len = command_len - strlen("exec ");
5128 base_offset += command_len + 1;
5132 * Insert <commands> after every pick. Here, fixup/squash chains
5133 * are considered part of the pick, so we insert the commands *after*
5134 * those chains if there are any.
5136 * As we insert the exec commands immediately after rearranging
5137 * any fixups and before the user edits the list, a fixup chain
5138 * can never contain comments (any comments are empty picks that
5139 * have been commented out because the user did not specify
5140 * --keep-empty). So, it is safe to insert an exec command
5141 * without looking at the command following a comment.
5143 insert = 0;
5144 for (i = 0; i < todo_list->nr; i++) {
5145 enum todo_command command = todo_list->items[i].command;
5146 if (insert && !is_fixup(command)) {
5147 ALLOC_GROW(items, nr + commands->nr, alloc);
5148 COPY_ARRAY(items + nr, base_items, commands->nr);
5149 nr += commands->nr;
5151 insert = 0;
5154 ALLOC_GROW(items, nr + 1, alloc);
5155 items[nr++] = todo_list->items[i];
5157 if (command == TODO_PICK || command == TODO_MERGE)
5158 insert = 1;
5161 /* insert or append final <commands> */
5162 if (insert || nr == todo_list->nr) {
5163 ALLOC_GROW(items, nr + commands->nr, alloc);
5164 COPY_ARRAY(items + nr, base_items, commands->nr);
5165 nr += commands->nr;
5168 free(base_items);
5169 FREE_AND_NULL(todo_list->items);
5170 todo_list->items = items;
5171 todo_list->nr = nr;
5172 todo_list->alloc = alloc;
5175 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5176 struct strbuf *buf, int num, unsigned flags)
5178 struct todo_item *item;
5179 int i, max = todo_list->nr;
5181 if (num > 0 && num < max)
5182 max = num;
5184 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5185 char cmd;
5187 /* if the item is not a command write it and continue */
5188 if (item->command >= TODO_COMMENT) {
5189 strbuf_addf(buf, "%.*s\n", item->arg_len,
5190 todo_item_get_arg(todo_list, item));
5191 continue;
5194 /* add command to the buffer */
5195 cmd = command_to_char(item->command);
5196 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5197 strbuf_addch(buf, cmd);
5198 else
5199 strbuf_addstr(buf, command_to_string(item->command));
5201 /* add commit id */
5202 if (item->commit) {
5203 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5204 short_commit_name(item->commit) :
5205 oid_to_hex(&item->commit->object.oid);
5207 if (item->command == TODO_MERGE) {
5208 if (item->flags & TODO_EDIT_MERGE_MSG)
5209 strbuf_addstr(buf, " -c");
5210 else
5211 strbuf_addstr(buf, " -C");
5214 strbuf_addf(buf, " %s", oid);
5217 /* add all the rest */
5218 if (!item->arg_len)
5219 strbuf_addch(buf, '\n');
5220 else
5221 strbuf_addf(buf, " %.*s\n", item->arg_len,
5222 todo_item_get_arg(todo_list, item));
5226 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5227 const char *file, const char *shortrevisions,
5228 const char *shortonto, int num, unsigned flags)
5230 int res;
5231 struct strbuf buf = STRBUF_INIT;
5233 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5234 if (flags & TODO_LIST_APPEND_TODO_HELP)
5235 append_todo_help(count_commands(todo_list),
5236 shortrevisions, shortonto, &buf);
5238 res = write_message(buf.buf, buf.len, file, 0);
5239 strbuf_release(&buf);
5241 return res;
5244 /* skip picking commits whose parents are unchanged */
5245 static int skip_unnecessary_picks(struct repository *r,
5246 struct todo_list *todo_list,
5247 struct object_id *base_oid)
5249 struct object_id *parent_oid;
5250 int i;
5252 for (i = 0; i < todo_list->nr; i++) {
5253 struct todo_item *item = todo_list->items + i;
5255 if (item->command >= TODO_NOOP)
5256 continue;
5257 if (item->command != TODO_PICK)
5258 break;
5259 if (parse_commit(item->commit)) {
5260 return error(_("could not parse commit '%s'"),
5261 oid_to_hex(&item->commit->object.oid));
5263 if (!item->commit->parents)
5264 break; /* root commit */
5265 if (item->commit->parents->next)
5266 break; /* merge commit */
5267 parent_oid = &item->commit->parents->item->object.oid;
5268 if (!oideq(parent_oid, base_oid))
5269 break;
5270 oidcpy(base_oid, &item->commit->object.oid);
5272 if (i > 0) {
5273 const char *done_path = rebase_path_done();
5275 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5276 error_errno(_("could not write to '%s'"), done_path);
5277 return -1;
5280 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5281 todo_list->nr -= i;
5282 todo_list->current = 0;
5283 todo_list->done_nr += i;
5285 if (is_fixup(peek_command(todo_list, 0)))
5286 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5289 return 0;
5292 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5293 const char *shortrevisions, const char *onto_name,
5294 struct commit *onto, const struct object_id *orig_head,
5295 struct string_list *commands, unsigned autosquash,
5296 struct todo_list *todo_list)
5298 char shortonto[GIT_MAX_HEXSZ + 1];
5299 const char *todo_file = rebase_path_todo();
5300 struct todo_list new_todo = TODO_LIST_INIT;
5301 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5302 struct object_id oid = onto->object.oid;
5303 int res;
5305 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5307 if (buf->len == 0) {
5308 struct todo_item *item = append_new_todo(todo_list);
5309 item->command = TODO_NOOP;
5310 item->commit = NULL;
5311 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5314 if (autosquash && todo_list_rearrange_squash(todo_list))
5315 return -1;
5317 if (commands->nr)
5318 todo_list_add_exec_commands(todo_list, commands);
5320 if (count_commands(todo_list) == 0) {
5321 apply_autostash(rebase_path_autostash());
5322 sequencer_remove_state(opts);
5324 return error(_("nothing to do"));
5327 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5328 shortonto, flags);
5329 if (res == -1)
5330 return -1;
5331 else if (res == -2) {
5332 apply_autostash(rebase_path_autostash());
5333 sequencer_remove_state(opts);
5335 return -1;
5336 } else if (res == -3) {
5337 apply_autostash(rebase_path_autostash());
5338 sequencer_remove_state(opts);
5339 todo_list_release(&new_todo);
5341 return error(_("nothing to do"));
5342 } else if (res == -4) {
5343 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5344 todo_list_release(&new_todo);
5346 return -1;
5349 /* Expand the commit IDs */
5350 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5351 strbuf_swap(&new_todo.buf, &buf2);
5352 strbuf_release(&buf2);
5353 new_todo.total_nr -= new_todo.nr;
5354 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5355 BUG("invalid todo list after expanding IDs:\n%s",
5356 new_todo.buf.buf);
5358 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5359 todo_list_release(&new_todo);
5360 return error(_("could not skip unnecessary pick commands"));
5363 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5364 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5365 todo_list_release(&new_todo);
5366 return error_errno(_("could not write '%s'"), todo_file);
5369 res = -1;
5371 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5372 goto cleanup;
5374 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5375 goto cleanup;
5377 todo_list_write_total_nr(&new_todo);
5378 res = pick_commits(r, &new_todo, opts);
5380 cleanup:
5381 todo_list_release(&new_todo);
5383 return res;
5386 struct subject2item_entry {
5387 struct hashmap_entry entry;
5388 int i;
5389 char subject[FLEX_ARRAY];
5392 static int subject2item_cmp(const void *fndata,
5393 const struct hashmap_entry *eptr,
5394 const struct hashmap_entry *entry_or_key,
5395 const void *key)
5397 const struct subject2item_entry *a, *b;
5399 a = container_of(eptr, const struct subject2item_entry, entry);
5400 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5402 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5405 define_commit_slab(commit_todo_item, struct todo_item *);
5408 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5409 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5410 * after the former, and change "pick" to "fixup"/"squash".
5412 * Note that if the config has specified a custom instruction format, each log
5413 * message will have to be retrieved from the commit (as the oneline in the
5414 * script cannot be trusted) in order to normalize the autosquash arrangement.
5416 int todo_list_rearrange_squash(struct todo_list *todo_list)
5418 struct hashmap subject2item;
5419 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5420 char **subjects;
5421 struct commit_todo_item commit_todo;
5422 struct todo_item *items = NULL;
5424 init_commit_todo_item(&commit_todo);
5426 * The hashmap maps onelines to the respective todo list index.
5428 * If any items need to be rearranged, the next[i] value will indicate
5429 * which item was moved directly after the i'th.
5431 * In that case, last[i] will indicate the index of the latest item to
5432 * be moved to appear after the i'th.
5434 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5435 ALLOC_ARRAY(next, todo_list->nr);
5436 ALLOC_ARRAY(tail, todo_list->nr);
5437 ALLOC_ARRAY(subjects, todo_list->nr);
5438 for (i = 0; i < todo_list->nr; i++) {
5439 struct strbuf buf = STRBUF_INIT;
5440 struct todo_item *item = todo_list->items + i;
5441 const char *commit_buffer, *subject, *p;
5442 size_t subject_len;
5443 int i2 = -1;
5444 struct subject2item_entry *entry;
5446 next[i] = tail[i] = -1;
5447 if (!item->commit || item->command == TODO_DROP) {
5448 subjects[i] = NULL;
5449 continue;
5452 if (is_fixup(item->command)) {
5453 clear_commit_todo_item(&commit_todo);
5454 return error(_("the script was already rearranged."));
5457 *commit_todo_item_at(&commit_todo, item->commit) = item;
5459 parse_commit(item->commit);
5460 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5461 find_commit_subject(commit_buffer, &subject);
5462 format_subject(&buf, subject, " ");
5463 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5464 unuse_commit_buffer(item->commit, commit_buffer);
5465 if ((skip_prefix(subject, "fixup! ", &p) ||
5466 skip_prefix(subject, "squash! ", &p))) {
5467 struct commit *commit2;
5469 for (;;) {
5470 while (isspace(*p))
5471 p++;
5472 if (!skip_prefix(p, "fixup! ", &p) &&
5473 !skip_prefix(p, "squash! ", &p))
5474 break;
5477 entry = hashmap_get_entry_from_hash(&subject2item,
5478 strhash(p), p,
5479 struct subject2item_entry,
5480 entry);
5481 if (entry)
5482 /* found by title */
5483 i2 = entry->i;
5484 else if (!strchr(p, ' ') &&
5485 (commit2 =
5486 lookup_commit_reference_by_name(p)) &&
5487 *commit_todo_item_at(&commit_todo, commit2))
5488 /* found by commit name */
5489 i2 = *commit_todo_item_at(&commit_todo, commit2)
5490 - todo_list->items;
5491 else {
5492 /* copy can be a prefix of the commit subject */
5493 for (i2 = 0; i2 < i; i2++)
5494 if (subjects[i2] &&
5495 starts_with(subjects[i2], p))
5496 break;
5497 if (i2 == i)
5498 i2 = -1;
5501 if (i2 >= 0) {
5502 rearranged = 1;
5503 todo_list->items[i].command =
5504 starts_with(subject, "fixup!") ?
5505 TODO_FIXUP : TODO_SQUASH;
5506 if (tail[i2] < 0) {
5507 next[i] = next[i2];
5508 next[i2] = i;
5509 } else {
5510 next[i] = next[tail[i2]];
5511 next[tail[i2]] = i;
5513 tail[i2] = i;
5514 } else if (!hashmap_get_from_hash(&subject2item,
5515 strhash(subject), subject)) {
5516 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5517 entry->i = i;
5518 hashmap_entry_init(&entry->entry,
5519 strhash(entry->subject));
5520 hashmap_put(&subject2item, &entry->entry);
5524 if (rearranged) {
5525 for (i = 0; i < todo_list->nr; i++) {
5526 enum todo_command command = todo_list->items[i].command;
5527 int cur = i;
5530 * Initially, all commands are 'pick's. If it is a
5531 * fixup or a squash now, we have rearranged it.
5533 if (is_fixup(command))
5534 continue;
5536 while (cur >= 0) {
5537 ALLOC_GROW(items, nr + 1, alloc);
5538 items[nr++] = todo_list->items[cur];
5539 cur = next[cur];
5543 FREE_AND_NULL(todo_list->items);
5544 todo_list->items = items;
5545 todo_list->nr = nr;
5546 todo_list->alloc = alloc;
5549 free(next);
5550 free(tail);
5551 for (i = 0; i < todo_list->nr; i++)
5552 free(subjects[i]);
5553 free(subjects);
5554 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5556 clear_commit_todo_item(&commit_todo);
5558 return 0;
5561 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5563 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5564 struct object_id cherry_pick_head, rebase_head;
5566 if (file_exists(git_path_seq_dir()))
5567 *whence = FROM_CHERRY_PICK_MULTI;
5568 if (file_exists(rebase_path()) &&
5569 !get_oid("REBASE_HEAD", &rebase_head) &&
5570 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5571 oideq(&rebase_head, &cherry_pick_head))
5572 *whence = FROM_REBASE_PICK;
5573 else
5574 *whence = FROM_CHERRY_PICK_SINGLE;
5576 return 1;
5579 return 0;