commit: extract cleanup_mode functions to sequencer
[alt-git.git] / sequencer.c
blob71636a3eb4321d481e4091b4bf4c1991c3df444c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "exec-cmd.h"
12 #include "utf8.h"
13 #include "cache-tree.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "rerere.h"
17 #include "merge-recursive.h"
18 #include "refs.h"
19 #include "argv-array.h"
20 #include "quote.h"
21 #include "trailer.h"
22 #include "log-tree.h"
23 #include "wt-status.h"
24 #include "hashmap.h"
25 #include "notes-utils.h"
26 #include "sigchain.h"
27 #include "unpack-trees.h"
28 #include "worktree.h"
29 #include "oidmap.h"
30 #include "oidset.h"
31 #include "commit-slab.h"
32 #include "alias.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 static GIT_PATH_FUNC(rebase_path_todo_backup,
59 "rebase-merge/git-rebase-todo.backup")
62 * The rebase command lines that have already been processed. A line
63 * is moved here when it is first handled, before any associated user
64 * actions.
66 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
68 * The file to keep track of how many commands were already processed (e.g.
69 * for the prompt).
71 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
73 * The file to keep track of how many commands are to be processed in total
74 * (e.g. for the prompt).
76 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
78 * The commit message that is planned to be used for any changes that
79 * need to be committed following a user interaction.
81 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
83 * The file into which is accumulated the suggested commit message for
84 * squash/fixup commands. When the first of a series of squash/fixups
85 * is seen, the file is created and the commit message from the
86 * previous commit and from the first squash/fixup commit are written
87 * to it. The commit message for each subsequent squash/fixup commit
88 * is appended to the file as it is processed.
90 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
92 * If the current series of squash/fixups has not yet included a squash
93 * command, then this file exists and holds the commit message of the
94 * original "pick" commit. (If the series ends without a "squash"
95 * command, then this can be used as the commit message of the combined
96 * commit without opening the editor.)
98 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
100 * This file contains the list fixup/squash commands that have been
101 * accumulated into message-fixup or message-squash so far.
103 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
105 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
106 * GIT_AUTHOR_DATE that will be used for the commit that is currently
107 * being rebased.
109 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
111 * When an "edit" rebase command is being processed, the SHA1 of the
112 * commit to be edited is recorded in this file. When "git rebase
113 * --continue" is executed, if there are any staged changes then they
114 * will be amended to the HEAD commit, but only provided the HEAD
115 * commit is still the commit to be edited. When any other rebase
116 * command is processed, this file is deleted.
118 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
120 * When we stop at a given patch via the "edit" command, this file contains
121 * the abbreviated commit name of the corresponding patch.
123 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
125 * For the post-rewrite hook, we make a list of rewritten commits and
126 * their new sha1s. The rewritten-pending list keeps the sha1s of
127 * commits that have been processed, but not committed yet,
128 * e.g. because they are waiting for a 'squash' command.
130 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
131 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
132 "rebase-merge/rewritten-pending")
135 * The path of the file containig the OID of the "squash onto" commit, i.e.
136 * the dummy commit used for `reset [new root]`.
138 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
141 * The path of the file listing refs that need to be deleted after the rebase
142 * finishes. This is used by the `label` command to record the need for cleanup.
144 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
147 * The following files are written by git-rebase just after parsing the
148 * command-line.
150 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
151 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
152 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
153 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
154 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
155 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
156 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
157 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
158 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
159 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
160 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
161 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
163 static int git_sequencer_config(const char *k, const char *v, void *cb)
165 struct replay_opts *opts = cb;
166 int status;
168 if (!strcmp(k, "commit.cleanup")) {
169 const char *s;
171 status = git_config_string(&s, k, v);
172 if (status)
173 return status;
175 if (!strcmp(s, "verbatim")) {
176 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
177 opts->explicit_cleanup = 1;
178 } else if (!strcmp(s, "whitespace")) {
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "strip")) {
182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "scissors")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
186 opts->explicit_cleanup = 1;
187 } else {
188 warning(_("invalid commit message cleanup mode '%s'"),
192 free((char *)s);
193 return status;
196 if (!strcmp(k, "commit.gpgsign")) {
197 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
198 return 0;
201 status = git_gpg_config(k, v, NULL);
202 if (status)
203 return status;
205 return git_diff_basic_config(k, v, NULL);
208 void sequencer_init_config(struct replay_opts *opts)
210 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
211 git_config(git_sequencer_config, opts);
214 static inline int is_rebase_i(const struct replay_opts *opts)
216 return opts->action == REPLAY_INTERACTIVE_REBASE;
219 static const char *get_dir(const struct replay_opts *opts)
221 if (is_rebase_i(opts))
222 return rebase_path();
223 return git_path_seq_dir();
226 static const char *get_todo_path(const struct replay_opts *opts)
228 if (is_rebase_i(opts))
229 return rebase_path_todo();
230 return git_path_todo_file();
234 * Returns 0 for non-conforming footer
235 * Returns 1 for conforming footer
236 * Returns 2 when sob exists within conforming footer
237 * Returns 3 when sob exists within conforming footer as last entry
239 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
240 size_t ignore_footer)
242 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
243 struct trailer_info info;
244 size_t i;
245 int found_sob = 0, found_sob_last = 0;
247 opts.no_divider = 1;
249 trailer_info_get(&info, sb->buf, &opts);
251 if (info.trailer_start == info.trailer_end)
252 return 0;
254 for (i = 0; i < info.trailer_nr; i++)
255 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
256 found_sob = 1;
257 if (i == info.trailer_nr - 1)
258 found_sob_last = 1;
261 trailer_info_release(&info);
263 if (found_sob_last)
264 return 3;
265 if (found_sob)
266 return 2;
267 return 1;
270 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
272 static struct strbuf buf = STRBUF_INIT;
274 strbuf_reset(&buf);
275 if (opts->gpg_sign)
276 sq_quotef(&buf, "-S%s", opts->gpg_sign);
277 return buf.buf;
280 int sequencer_remove_state(struct replay_opts *opts)
282 struct strbuf buf = STRBUF_INIT;
283 int i;
285 if (is_rebase_i(opts) &&
286 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
287 char *p = buf.buf;
288 while (*p) {
289 char *eol = strchr(p, '\n');
290 if (eol)
291 *eol = '\0';
292 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
293 warning(_("could not delete '%s'"), p);
294 if (!eol)
295 break;
296 p = eol + 1;
300 free(opts->gpg_sign);
301 free(opts->strategy);
302 for (i = 0; i < opts->xopts_nr; i++)
303 free(opts->xopts[i]);
304 free(opts->xopts);
305 strbuf_release(&opts->current_fixups);
307 strbuf_reset(&buf);
308 strbuf_addstr(&buf, get_dir(opts));
309 remove_dir_recursively(&buf, 0);
310 strbuf_release(&buf);
312 return 0;
315 static const char *action_name(const struct replay_opts *opts)
317 switch (opts->action) {
318 case REPLAY_REVERT:
319 return N_("revert");
320 case REPLAY_PICK:
321 return N_("cherry-pick");
322 case REPLAY_INTERACTIVE_REBASE:
323 return N_("rebase -i");
325 die(_("unknown action: %d"), opts->action);
328 struct commit_message {
329 char *parent_label;
330 char *label;
331 char *subject;
332 const char *message;
335 static const char *short_commit_name(struct commit *commit)
337 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
340 static int get_message(struct commit *commit, struct commit_message *out)
342 const char *abbrev, *subject;
343 int subject_len;
345 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
346 abbrev = short_commit_name(commit);
348 subject_len = find_commit_subject(out->message, &subject);
350 out->subject = xmemdupz(subject, subject_len);
351 out->label = xstrfmt("%s... %s", abbrev, out->subject);
352 out->parent_label = xstrfmt("parent of %s", out->label);
354 return 0;
357 static void free_message(struct commit *commit, struct commit_message *msg)
359 free(msg->parent_label);
360 free(msg->label);
361 free(msg->subject);
362 unuse_commit_buffer(commit, msg->message);
365 static void print_advice(struct repository *r, int show_hint,
366 struct replay_opts *opts)
368 char *msg = getenv("GIT_CHERRY_PICK_HELP");
370 if (msg) {
371 fprintf(stderr, "%s\n", msg);
373 * A conflict has occurred but the porcelain
374 * (typically rebase --interactive) wants to take care
375 * of the commit itself so remove CHERRY_PICK_HEAD
377 unlink(git_path_cherry_pick_head(r));
378 return;
381 if (show_hint) {
382 if (opts->no_commit)
383 advise(_("after resolving the conflicts, mark the corrected paths\n"
384 "with 'git add <paths>' or 'git rm <paths>'"));
385 else
386 advise(_("after resolving the conflicts, mark the corrected paths\n"
387 "with 'git add <paths>' or 'git rm <paths>'\n"
388 "and commit the result with 'git commit'"));
392 int write_message(const void *buf, size_t len, const char *filename,
393 int append_eol)
395 struct lock_file msg_file = LOCK_INIT;
397 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
398 if (msg_fd < 0)
399 return error_errno(_("could not lock '%s'"), filename);
400 if (write_in_full(msg_fd, buf, len) < 0) {
401 error_errno(_("could not write to '%s'"), filename);
402 rollback_lock_file(&msg_file);
403 return -1;
405 if (append_eol && write(msg_fd, "\n", 1) < 0) {
406 error_errno(_("could not write eol to '%s'"), filename);
407 rollback_lock_file(&msg_file);
408 return -1;
410 if (commit_lock_file(&msg_file) < 0)
411 return error(_("failed to finalize '%s'"), filename);
413 return 0;
417 * Reads a file that was presumably written by a shell script, i.e. with an
418 * end-of-line marker that needs to be stripped.
420 * Note that only the last end-of-line marker is stripped, consistent with the
421 * behavior of "$(cat path)" in a shell script.
423 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
425 static int read_oneliner(struct strbuf *buf,
426 const char *path, int skip_if_empty)
428 int orig_len = buf->len;
430 if (!file_exists(path))
431 return 0;
433 if (strbuf_read_file(buf, path, 0) < 0) {
434 warning_errno(_("could not read '%s'"), path);
435 return 0;
438 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
439 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
440 --buf->len;
441 buf->buf[buf->len] = '\0';
444 if (skip_if_empty && buf->len == orig_len)
445 return 0;
447 return 1;
450 static struct tree *empty_tree(struct repository *r)
452 return lookup_tree(r, the_hash_algo->empty_tree);
455 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
457 if (repo_read_index_unmerged(repo))
458 return error_resolve_conflict(_(action_name(opts)));
460 error(_("your local changes would be overwritten by %s."),
461 _(action_name(opts)));
463 if (advice_commit_before_merge)
464 advise(_("commit your changes or stash them to proceed."));
465 return -1;
468 static void update_abort_safety_file(void)
470 struct object_id head;
472 /* Do nothing on a single-pick */
473 if (!file_exists(git_path_seq_dir()))
474 return;
476 if (!get_oid("HEAD", &head))
477 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
478 else
479 write_file(git_path_abort_safety_file(), "%s", "");
482 static int fast_forward_to(struct repository *r,
483 const struct object_id *to,
484 const struct object_id *from,
485 int unborn,
486 struct replay_opts *opts)
488 struct ref_transaction *transaction;
489 struct strbuf sb = STRBUF_INIT;
490 struct strbuf err = STRBUF_INIT;
492 repo_read_index(r);
493 if (checkout_fast_forward(r, from, to, 1))
494 return -1; /* the callee should have complained already */
496 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
498 transaction = ref_transaction_begin(&err);
499 if (!transaction ||
500 ref_transaction_update(transaction, "HEAD",
501 to, unborn && !is_rebase_i(opts) ?
502 &null_oid : from,
503 0, sb.buf, &err) ||
504 ref_transaction_commit(transaction, &err)) {
505 ref_transaction_free(transaction);
506 error("%s", err.buf);
507 strbuf_release(&sb);
508 strbuf_release(&err);
509 return -1;
512 strbuf_release(&sb);
513 strbuf_release(&err);
514 ref_transaction_free(transaction);
515 update_abort_safety_file();
516 return 0;
519 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
520 int use_editor)
522 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
523 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
524 COMMIT_MSG_CLEANUP_SPACE;
525 else if (!strcmp(cleanup_arg, "verbatim"))
526 return COMMIT_MSG_CLEANUP_NONE;
527 else if (!strcmp(cleanup_arg, "whitespace"))
528 return COMMIT_MSG_CLEANUP_SPACE;
529 else if (!strcmp(cleanup_arg, "strip"))
530 return COMMIT_MSG_CLEANUP_ALL;
531 else if (!strcmp(cleanup_arg, "scissors"))
532 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
533 COMMIT_MSG_CLEANUP_SPACE;
534 else
535 die(_("Invalid cleanup mode %s"), cleanup_arg);
538 void append_conflicts_hint(struct index_state *istate,
539 struct strbuf *msgbuf)
541 int i;
543 strbuf_addch(msgbuf, '\n');
544 strbuf_commented_addf(msgbuf, "Conflicts:\n");
545 for (i = 0; i < istate->cache_nr;) {
546 const struct cache_entry *ce = istate->cache[i++];
547 if (ce_stage(ce)) {
548 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
549 while (i < istate->cache_nr &&
550 !strcmp(ce->name, istate->cache[i]->name))
551 i++;
556 static int do_recursive_merge(struct repository *r,
557 struct commit *base, struct commit *next,
558 const char *base_label, const char *next_label,
559 struct object_id *head, struct strbuf *msgbuf,
560 struct replay_opts *opts)
562 struct merge_options o;
563 struct tree *result, *next_tree, *base_tree, *head_tree;
564 int clean;
565 char **xopt;
566 struct lock_file index_lock = LOCK_INIT;
568 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
569 return -1;
571 repo_read_index(r);
573 init_merge_options(&o, r);
574 o.ancestor = base ? base_label : "(empty tree)";
575 o.branch1 = "HEAD";
576 o.branch2 = next ? next_label : "(empty tree)";
577 if (is_rebase_i(opts))
578 o.buffer_output = 2;
579 o.show_rename_progress = 1;
581 head_tree = parse_tree_indirect(head);
582 next_tree = next ? get_commit_tree(next) : empty_tree(r);
583 base_tree = base ? get_commit_tree(base) : empty_tree(r);
585 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
586 parse_merge_opt(&o, *xopt);
588 clean = merge_trees(&o,
589 head_tree,
590 next_tree, base_tree, &result);
591 if (is_rebase_i(opts) && clean <= 0)
592 fputs(o.obuf.buf, stdout);
593 strbuf_release(&o.obuf);
594 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
595 if (clean < 0) {
596 rollback_lock_file(&index_lock);
597 return clean;
600 if (write_locked_index(r->index, &index_lock,
601 COMMIT_LOCK | SKIP_IF_UNCHANGED))
603 * TRANSLATORS: %s will be "revert", "cherry-pick" or
604 * "rebase -i".
606 return error(_("%s: Unable to write new index file"),
607 _(action_name(opts)));
609 if (!clean)
610 append_conflicts_hint(r->index, msgbuf);
612 return !clean;
615 static struct object_id *get_cache_tree_oid(struct index_state *istate)
617 if (!istate->cache_tree)
618 istate->cache_tree = cache_tree();
620 if (!cache_tree_fully_valid(istate->cache_tree))
621 if (cache_tree_update(istate, 0)) {
622 error(_("unable to update cache tree"));
623 return NULL;
626 return &istate->cache_tree->oid;
629 static int is_index_unchanged(struct repository *r)
631 struct object_id head_oid, *cache_tree_oid;
632 struct commit *head_commit;
633 struct index_state *istate = r->index;
635 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
636 return error(_("could not resolve HEAD commit"));
638 head_commit = lookup_commit(r, &head_oid);
641 * If head_commit is NULL, check_commit, called from
642 * lookup_commit, would have indicated that head_commit is not
643 * a commit object already. parse_commit() will return failure
644 * without further complaints in such a case. Otherwise, if
645 * the commit is invalid, parse_commit() will complain. So
646 * there is nothing for us to say here. Just return failure.
648 if (parse_commit(head_commit))
649 return -1;
651 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
652 return -1;
654 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
657 static int write_author_script(const char *message)
659 struct strbuf buf = STRBUF_INIT;
660 const char *eol;
661 int res;
663 for (;;)
664 if (!*message || starts_with(message, "\n")) {
665 missing_author:
666 /* Missing 'author' line? */
667 unlink(rebase_path_author_script());
668 return 0;
669 } else if (skip_prefix(message, "author ", &message))
670 break;
671 else if ((eol = strchr(message, '\n')))
672 message = eol + 1;
673 else
674 goto missing_author;
676 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
677 while (*message && *message != '\n' && *message != '\r')
678 if (skip_prefix(message, " <", &message))
679 break;
680 else if (*message != '\'')
681 strbuf_addch(&buf, *(message++));
682 else
683 strbuf_addf(&buf, "'\\%c'", *(message++));
684 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
685 while (*message && *message != '\n' && *message != '\r')
686 if (skip_prefix(message, "> ", &message))
687 break;
688 else if (*message != '\'')
689 strbuf_addch(&buf, *(message++));
690 else
691 strbuf_addf(&buf, "'\\%c'", *(message++));
692 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
693 while (*message && *message != '\n' && *message != '\r')
694 if (*message != '\'')
695 strbuf_addch(&buf, *(message++));
696 else
697 strbuf_addf(&buf, "'\\%c'", *(message++));
698 strbuf_addch(&buf, '\'');
699 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
700 strbuf_release(&buf);
701 return res;
705 * Take a series of KEY='VALUE' lines where VALUE part is
706 * sq-quoted, and append <KEY, VALUE> at the end of the string list
708 static int parse_key_value_squoted(char *buf, struct string_list *list)
710 while (*buf) {
711 struct string_list_item *item;
712 char *np;
713 char *cp = strchr(buf, '=');
714 if (!cp) {
715 np = strchrnul(buf, '\n');
716 return error(_("no key present in '%.*s'"),
717 (int) (np - buf), buf);
719 np = strchrnul(cp, '\n');
720 *cp++ = '\0';
721 item = string_list_append(list, buf);
723 buf = np + (*np == '\n');
724 *np = '\0';
725 cp = sq_dequote(cp);
726 if (!cp)
727 return error(_("unable to dequote value of '%s'"),
728 item->string);
729 item->util = xstrdup(cp);
731 return 0;
735 * Reads and parses the state directory's "author-script" file, and sets name,
736 * email and date accordingly.
737 * Returns 0 on success, -1 if the file could not be parsed.
739 * The author script is of the format:
741 * GIT_AUTHOR_NAME='$author_name'
742 * GIT_AUTHOR_EMAIL='$author_email'
743 * GIT_AUTHOR_DATE='$author_date'
745 * where $author_name, $author_email and $author_date are quoted. We are strict
746 * with our parsing, as the file was meant to be eval'd in the old
747 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
748 * from what this function expects, it is better to bail out than to do
749 * something that the user does not expect.
751 int read_author_script(const char *path, char **name, char **email, char **date,
752 int allow_missing)
754 struct strbuf buf = STRBUF_INIT;
755 struct string_list kv = STRING_LIST_INIT_DUP;
756 int retval = -1; /* assume failure */
757 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
759 if (strbuf_read_file(&buf, path, 256) <= 0) {
760 strbuf_release(&buf);
761 if (errno == ENOENT && allow_missing)
762 return 0;
763 else
764 return error_errno(_("could not open '%s' for reading"),
765 path);
768 if (parse_key_value_squoted(buf.buf, &kv))
769 goto finish;
771 for (i = 0; i < kv.nr; i++) {
772 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
773 if (name_i != -2)
774 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
775 else
776 name_i = i;
777 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
778 if (email_i != -2)
779 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
780 else
781 email_i = i;
782 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
783 if (date_i != -2)
784 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
785 else
786 date_i = i;
787 } else {
788 err = error(_("unknown variable '%s'"),
789 kv.items[i].string);
792 if (name_i == -2)
793 error(_("missing 'GIT_AUTHOR_NAME'"));
794 if (email_i == -2)
795 error(_("missing 'GIT_AUTHOR_EMAIL'"));
796 if (date_i == -2)
797 error(_("missing 'GIT_AUTHOR_DATE'"));
798 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
799 goto finish;
800 *name = kv.items[name_i].util;
801 *email = kv.items[email_i].util;
802 *date = kv.items[date_i].util;
803 retval = 0;
804 finish:
805 string_list_clear(&kv, !!retval);
806 strbuf_release(&buf);
807 return retval;
811 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
812 * file with shell quoting into struct argv_array. Returns -1 on
813 * error, 0 otherwise.
815 static int read_env_script(struct argv_array *env)
817 char *name, *email, *date;
819 if (read_author_script(rebase_path_author_script(),
820 &name, &email, &date, 0))
821 return -1;
823 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
824 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
825 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
826 free(name);
827 free(email);
828 free(date);
830 return 0;
833 static char *get_author(const char *message)
835 size_t len;
836 const char *a;
838 a = find_commit_header(message, "author", &len);
839 if (a)
840 return xmemdupz(a, len);
842 return NULL;
845 /* Read author-script and return an ident line (author <email> timestamp) */
846 static const char *read_author_ident(struct strbuf *buf)
848 struct strbuf out = STRBUF_INIT;
849 char *name, *email, *date;
851 if (read_author_script(rebase_path_author_script(),
852 &name, &email, &date, 0))
853 return NULL;
855 /* validate date since fmt_ident() will die() on bad value */
856 if (parse_date(date, &out)){
857 warning(_("invalid date format '%s' in '%s'"),
858 date, rebase_path_author_script());
859 strbuf_release(&out);
860 return NULL;
863 strbuf_reset(&out);
864 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
865 strbuf_swap(buf, &out);
866 strbuf_release(&out);
867 free(name);
868 free(email);
869 free(date);
870 return buf->buf;
873 static const char staged_changes_advice[] =
874 N_("you have staged changes in your working tree\n"
875 "If these changes are meant to be squashed into the previous commit, run:\n"
876 "\n"
877 " git commit --amend %s\n"
878 "\n"
879 "If they are meant to go into a new commit, run:\n"
880 "\n"
881 " git commit %s\n"
882 "\n"
883 "In both cases, once you're done, continue with:\n"
884 "\n"
885 " git rebase --continue\n");
887 #define ALLOW_EMPTY (1<<0)
888 #define EDIT_MSG (1<<1)
889 #define AMEND_MSG (1<<2)
890 #define CLEANUP_MSG (1<<3)
891 #define VERIFY_MSG (1<<4)
892 #define CREATE_ROOT_COMMIT (1<<5)
894 static int run_command_silent_on_success(struct child_process *cmd)
896 struct strbuf buf = STRBUF_INIT;
897 int rc;
899 cmd->stdout_to_stderr = 1;
900 rc = pipe_command(cmd,
901 NULL, 0,
902 NULL, 0,
903 &buf, 0);
905 if (rc)
906 fputs(buf.buf, stderr);
907 strbuf_release(&buf);
908 return rc;
912 * If we are cherry-pick, and if the merge did not result in
913 * hand-editing, we will hit this commit and inherit the original
914 * author date and name.
916 * If we are revert, or if our cherry-pick results in a hand merge,
917 * we had better say that the current user is responsible for that.
919 * An exception is when run_git_commit() is called during an
920 * interactive rebase: in that case, we will want to retain the
921 * author metadata.
923 static int run_git_commit(struct repository *r,
924 const char *defmsg,
925 struct replay_opts *opts,
926 unsigned int flags)
928 struct child_process cmd = CHILD_PROCESS_INIT;
929 const char *value;
931 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
932 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
933 const char *author = NULL;
934 struct object_id root_commit, *cache_tree_oid;
935 int res = 0;
937 if (is_rebase_i(opts)) {
938 author = read_author_ident(&script);
939 if (!author) {
940 strbuf_release(&script);
941 return -1;
945 if (!defmsg)
946 BUG("root commit without message");
948 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
949 res = -1;
951 if (!res)
952 res = strbuf_read_file(&msg, defmsg, 0);
954 if (res <= 0)
955 res = error_errno(_("could not read '%s'"), defmsg);
956 else
957 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
958 NULL, &root_commit, author,
959 opts->gpg_sign);
961 strbuf_release(&msg);
962 strbuf_release(&script);
963 if (!res) {
964 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
965 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
966 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
967 UPDATE_REFS_MSG_ON_ERR);
969 return res < 0 ? error(_("writing root commit")) : 0;
972 cmd.git_cmd = 1;
974 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
975 const char *gpg_opt = gpg_sign_opt_quoted(opts);
977 return error(_(staged_changes_advice),
978 gpg_opt, gpg_opt);
981 argv_array_push(&cmd.args, "commit");
983 if (!(flags & VERIFY_MSG))
984 argv_array_push(&cmd.args, "-n");
985 if ((flags & AMEND_MSG))
986 argv_array_push(&cmd.args, "--amend");
987 if (opts->gpg_sign)
988 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
989 if (defmsg)
990 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
991 else if (!(flags & EDIT_MSG))
992 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
993 if ((flags & CLEANUP_MSG))
994 argv_array_push(&cmd.args, "--cleanup=strip");
995 if ((flags & EDIT_MSG))
996 argv_array_push(&cmd.args, "-e");
997 else if (!(flags & CLEANUP_MSG) &&
998 !opts->signoff && !opts->record_origin &&
999 git_config_get_value("commit.cleanup", &value))
1000 argv_array_push(&cmd.args, "--cleanup=verbatim");
1002 if ((flags & ALLOW_EMPTY))
1003 argv_array_push(&cmd.args, "--allow-empty");
1005 if (!(flags & EDIT_MSG))
1006 argv_array_push(&cmd.args, "--allow-empty-message");
1008 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1009 return run_command_silent_on_success(&cmd);
1010 else
1011 return run_command(&cmd);
1014 static int rest_is_empty(const struct strbuf *sb, int start)
1016 int i, eol;
1017 const char *nl;
1019 /* Check if the rest is just whitespace and Signed-off-by's. */
1020 for (i = start; i < sb->len; i++) {
1021 nl = memchr(sb->buf + i, '\n', sb->len - i);
1022 if (nl)
1023 eol = nl - sb->buf;
1024 else
1025 eol = sb->len;
1027 if (strlen(sign_off_header) <= eol - i &&
1028 starts_with(sb->buf + i, sign_off_header)) {
1029 i = eol;
1030 continue;
1032 while (i < eol)
1033 if (!isspace(sb->buf[i++]))
1034 return 0;
1037 return 1;
1040 void cleanup_message(struct strbuf *msgbuf,
1041 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1043 if (verbose || /* Truncate the message just before the diff, if any. */
1044 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1045 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1046 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1047 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1051 * Find out if the message in the strbuf contains only whitespace and
1052 * Signed-off-by lines.
1054 int message_is_empty(const struct strbuf *sb,
1055 enum commit_msg_cleanup_mode cleanup_mode)
1057 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1058 return 0;
1059 return rest_is_empty(sb, 0);
1063 * See if the user edited the message in the editor or left what
1064 * was in the template intact
1066 int template_untouched(const struct strbuf *sb, const char *template_file,
1067 enum commit_msg_cleanup_mode cleanup_mode)
1069 struct strbuf tmpl = STRBUF_INIT;
1070 const char *start;
1072 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1073 return 0;
1075 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1076 return 0;
1078 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1079 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1080 start = sb->buf;
1081 strbuf_release(&tmpl);
1082 return rest_is_empty(sb, start - sb->buf);
1085 int update_head_with_reflog(const struct commit *old_head,
1086 const struct object_id *new_head,
1087 const char *action, const struct strbuf *msg,
1088 struct strbuf *err)
1090 struct ref_transaction *transaction;
1091 struct strbuf sb = STRBUF_INIT;
1092 const char *nl;
1093 int ret = 0;
1095 if (action) {
1096 strbuf_addstr(&sb, action);
1097 strbuf_addstr(&sb, ": ");
1100 nl = strchr(msg->buf, '\n');
1101 if (nl) {
1102 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1103 } else {
1104 strbuf_addbuf(&sb, msg);
1105 strbuf_addch(&sb, '\n');
1108 transaction = ref_transaction_begin(err);
1109 if (!transaction ||
1110 ref_transaction_update(transaction, "HEAD", new_head,
1111 old_head ? &old_head->object.oid : &null_oid,
1112 0, sb.buf, err) ||
1113 ref_transaction_commit(transaction, err)) {
1114 ret = -1;
1116 ref_transaction_free(transaction);
1117 strbuf_release(&sb);
1119 return ret;
1122 static int run_rewrite_hook(const struct object_id *oldoid,
1123 const struct object_id *newoid)
1125 struct child_process proc = CHILD_PROCESS_INIT;
1126 const char *argv[3];
1127 int code;
1128 struct strbuf sb = STRBUF_INIT;
1130 argv[0] = find_hook("post-rewrite");
1131 if (!argv[0])
1132 return 0;
1134 argv[1] = "amend";
1135 argv[2] = NULL;
1137 proc.argv = argv;
1138 proc.in = -1;
1139 proc.stdout_to_stderr = 1;
1140 proc.trace2_hook_name = "post-rewrite";
1142 code = start_command(&proc);
1143 if (code)
1144 return code;
1145 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1146 sigchain_push(SIGPIPE, SIG_IGN);
1147 write_in_full(proc.in, sb.buf, sb.len);
1148 close(proc.in);
1149 strbuf_release(&sb);
1150 sigchain_pop(SIGPIPE);
1151 return finish_command(&proc);
1154 void commit_post_rewrite(struct repository *r,
1155 const struct commit *old_head,
1156 const struct object_id *new_head)
1158 struct notes_rewrite_cfg *cfg;
1160 cfg = init_copy_notes_for_rewrite("amend");
1161 if (cfg) {
1162 /* we are amending, so old_head is not NULL */
1163 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1164 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1166 run_rewrite_hook(&old_head->object.oid, new_head);
1169 static int run_prepare_commit_msg_hook(struct repository *r,
1170 struct strbuf *msg,
1171 const char *commit)
1173 struct argv_array hook_env = ARGV_ARRAY_INIT;
1174 int ret;
1175 const char *name;
1177 name = git_path_commit_editmsg();
1178 if (write_message(msg->buf, msg->len, name, 0))
1179 return -1;
1181 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
1182 argv_array_push(&hook_env, "GIT_EDITOR=:");
1183 if (commit)
1184 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1185 "commit", commit, NULL);
1186 else
1187 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1188 "message", NULL);
1189 if (ret)
1190 ret = error(_("'prepare-commit-msg' hook failed"));
1191 argv_array_clear(&hook_env);
1193 return ret;
1196 static const char implicit_ident_advice_noconfig[] =
1197 N_("Your name and email address were configured automatically based\n"
1198 "on your username and hostname. Please check that they are accurate.\n"
1199 "You can suppress this message by setting them explicitly. Run the\n"
1200 "following command and follow the instructions in your editor to edit\n"
1201 "your configuration file:\n"
1202 "\n"
1203 " git config --global --edit\n"
1204 "\n"
1205 "After doing this, you may fix the identity used for this commit with:\n"
1206 "\n"
1207 " git commit --amend --reset-author\n");
1209 static const char implicit_ident_advice_config[] =
1210 N_("Your name and email address were configured automatically based\n"
1211 "on your username and hostname. Please check that they are accurate.\n"
1212 "You can suppress this message by setting them explicitly:\n"
1213 "\n"
1214 " git config --global user.name \"Your Name\"\n"
1215 " git config --global user.email you@example.com\n"
1216 "\n"
1217 "After doing this, you may fix the identity used for this commit with:\n"
1218 "\n"
1219 " git commit --amend --reset-author\n");
1221 static const char *implicit_ident_advice(void)
1223 char *user_config = expand_user_path("~/.gitconfig", 0);
1224 char *xdg_config = xdg_config_home("config");
1225 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1227 free(user_config);
1228 free(xdg_config);
1230 if (config_exists)
1231 return _(implicit_ident_advice_config);
1232 else
1233 return _(implicit_ident_advice_noconfig);
1237 void print_commit_summary(struct repository *r,
1238 const char *prefix,
1239 const struct object_id *oid,
1240 unsigned int flags)
1242 struct rev_info rev;
1243 struct commit *commit;
1244 struct strbuf format = STRBUF_INIT;
1245 const char *head;
1246 struct pretty_print_context pctx = {0};
1247 struct strbuf author_ident = STRBUF_INIT;
1248 struct strbuf committer_ident = STRBUF_INIT;
1250 commit = lookup_commit(r, oid);
1251 if (!commit)
1252 die(_("couldn't look up newly created commit"));
1253 if (parse_commit(commit))
1254 die(_("could not parse newly created commit"));
1256 strbuf_addstr(&format, "format:%h] %s");
1258 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1259 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1260 if (strbuf_cmp(&author_ident, &committer_ident)) {
1261 strbuf_addstr(&format, "\n Author: ");
1262 strbuf_addbuf_percentquote(&format, &author_ident);
1264 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1265 struct strbuf date = STRBUF_INIT;
1267 format_commit_message(commit, "%ad", &date, &pctx);
1268 strbuf_addstr(&format, "\n Date: ");
1269 strbuf_addbuf_percentquote(&format, &date);
1270 strbuf_release(&date);
1272 if (!committer_ident_sufficiently_given()) {
1273 strbuf_addstr(&format, "\n Committer: ");
1274 strbuf_addbuf_percentquote(&format, &committer_ident);
1275 if (advice_implicit_identity) {
1276 strbuf_addch(&format, '\n');
1277 strbuf_addstr(&format, implicit_ident_advice());
1280 strbuf_release(&author_ident);
1281 strbuf_release(&committer_ident);
1283 repo_init_revisions(r, &rev, prefix);
1284 setup_revisions(0, NULL, &rev, NULL);
1286 rev.diff = 1;
1287 rev.diffopt.output_format =
1288 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1290 rev.verbose_header = 1;
1291 rev.show_root_diff = 1;
1292 get_commit_format(format.buf, &rev);
1293 rev.always_show_header = 0;
1294 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1295 rev.diffopt.break_opt = 0;
1296 diff_setup_done(&rev.diffopt);
1298 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1299 if (!head)
1300 die_errno(_("unable to resolve HEAD after creating commit"));
1301 if (!strcmp(head, "HEAD"))
1302 head = _("detached HEAD");
1303 else
1304 skip_prefix(head, "refs/heads/", &head);
1305 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1306 _(" (root-commit)") : "");
1308 if (!log_tree_commit(&rev, commit)) {
1309 rev.always_show_header = 1;
1310 rev.use_terminator = 1;
1311 log_tree_commit(&rev, commit);
1314 strbuf_release(&format);
1317 static int parse_head(struct repository *r, struct commit **head)
1319 struct commit *current_head;
1320 struct object_id oid;
1322 if (get_oid("HEAD", &oid)) {
1323 current_head = NULL;
1324 } else {
1325 current_head = lookup_commit_reference(r, &oid);
1326 if (!current_head)
1327 return error(_("could not parse HEAD"));
1328 if (!oideq(&oid, &current_head->object.oid)) {
1329 warning(_("HEAD %s is not a commit!"),
1330 oid_to_hex(&oid));
1332 if (parse_commit(current_head))
1333 return error(_("could not parse HEAD commit"));
1335 *head = current_head;
1337 return 0;
1341 * Try to commit without forking 'git commit'. In some cases we need
1342 * to run 'git commit' to display an error message
1344 * Returns:
1345 * -1 - error unable to commit
1346 * 0 - success
1347 * 1 - run 'git commit'
1349 static int try_to_commit(struct repository *r,
1350 struct strbuf *msg, const char *author,
1351 struct replay_opts *opts, unsigned int flags,
1352 struct object_id *oid)
1354 struct object_id tree;
1355 struct commit *current_head;
1356 struct commit_list *parents = NULL;
1357 struct commit_extra_header *extra = NULL;
1358 struct strbuf err = STRBUF_INIT;
1359 struct strbuf commit_msg = STRBUF_INIT;
1360 char *amend_author = NULL;
1361 const char *hook_commit = NULL;
1362 enum commit_msg_cleanup_mode cleanup;
1363 int res = 0;
1365 if (parse_head(r, &current_head))
1366 return -1;
1368 if (flags & AMEND_MSG) {
1369 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1370 const char *out_enc = get_commit_output_encoding();
1371 const char *message = logmsg_reencode(current_head, NULL,
1372 out_enc);
1374 if (!msg) {
1375 const char *orig_message = NULL;
1377 find_commit_subject(message, &orig_message);
1378 msg = &commit_msg;
1379 strbuf_addstr(msg, orig_message);
1380 hook_commit = "HEAD";
1382 author = amend_author = get_author(message);
1383 unuse_commit_buffer(current_head, message);
1384 if (!author) {
1385 res = error(_("unable to parse commit author"));
1386 goto out;
1388 parents = copy_commit_list(current_head->parents);
1389 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1390 } else if (current_head) {
1391 commit_list_insert(current_head, &parents);
1394 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1395 res = error(_("git write-tree failed to write a tree"));
1396 goto out;
1399 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1400 get_commit_tree_oid(current_head) :
1401 the_hash_algo->empty_tree, &tree)) {
1402 res = 1; /* run 'git commit' to display error message */
1403 goto out;
1406 if (find_hook("prepare-commit-msg")) {
1407 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1408 if (res)
1409 goto out;
1410 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1411 2048) < 0) {
1412 res = error_errno(_("unable to read commit message "
1413 "from '%s'"),
1414 git_path_commit_editmsg());
1415 goto out;
1417 msg = &commit_msg;
1420 if (flags & CLEANUP_MSG)
1421 cleanup = COMMIT_MSG_CLEANUP_ALL;
1422 else if ((opts->signoff || opts->record_origin) &&
1423 !opts->explicit_cleanup)
1424 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1425 else
1426 cleanup = opts->default_msg_cleanup;
1428 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1429 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1430 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1431 res = 1; /* run 'git commit' to display error message */
1432 goto out;
1435 reset_ident_date();
1437 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1438 oid, author, opts->gpg_sign, extra)) {
1439 res = error(_("failed to write commit object"));
1440 goto out;
1443 if (update_head_with_reflog(current_head, oid,
1444 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1445 res = error("%s", err.buf);
1446 goto out;
1449 if (flags & AMEND_MSG)
1450 commit_post_rewrite(r, current_head, oid);
1452 out:
1453 free_commit_extra_headers(extra);
1454 strbuf_release(&err);
1455 strbuf_release(&commit_msg);
1456 free(amend_author);
1458 return res;
1461 static int do_commit(struct repository *r,
1462 const char *msg_file, const char *author,
1463 struct replay_opts *opts, unsigned int flags)
1465 int res = 1;
1467 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1468 !(flags & CREATE_ROOT_COMMIT)) {
1469 struct object_id oid;
1470 struct strbuf sb = STRBUF_INIT;
1472 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1473 return error_errno(_("unable to read commit message "
1474 "from '%s'"),
1475 msg_file);
1477 res = try_to_commit(r, msg_file ? &sb : NULL,
1478 author, opts, flags, &oid);
1479 strbuf_release(&sb);
1480 if (!res) {
1481 unlink(git_path_cherry_pick_head(r));
1482 unlink(git_path_merge_msg(r));
1483 if (!is_rebase_i(opts))
1484 print_commit_summary(r, NULL, &oid,
1485 SUMMARY_SHOW_AUTHOR_DATE);
1486 return res;
1489 if (res == 1)
1490 return run_git_commit(r, msg_file, opts, flags);
1492 return res;
1495 static int is_original_commit_empty(struct commit *commit)
1497 const struct object_id *ptree_oid;
1499 if (parse_commit(commit))
1500 return error(_("could not parse commit %s"),
1501 oid_to_hex(&commit->object.oid));
1502 if (commit->parents) {
1503 struct commit *parent = commit->parents->item;
1504 if (parse_commit(parent))
1505 return error(_("could not parse parent commit %s"),
1506 oid_to_hex(&parent->object.oid));
1507 ptree_oid = get_commit_tree_oid(parent);
1508 } else {
1509 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1512 return oideq(ptree_oid, get_commit_tree_oid(commit));
1516 * Do we run "git commit" with "--allow-empty"?
1518 static int allow_empty(struct repository *r,
1519 struct replay_opts *opts,
1520 struct commit *commit)
1522 int index_unchanged, empty_commit;
1525 * Three cases:
1527 * (1) we do not allow empty at all and error out.
1529 * (2) we allow ones that were initially empty, but
1530 * forbid the ones that become empty;
1532 * (3) we allow both.
1534 if (!opts->allow_empty)
1535 return 0; /* let "git commit" barf as necessary */
1537 index_unchanged = is_index_unchanged(r);
1538 if (index_unchanged < 0)
1539 return index_unchanged;
1540 if (!index_unchanged)
1541 return 0; /* we do not have to say --allow-empty */
1543 if (opts->keep_redundant_commits)
1544 return 1;
1546 empty_commit = is_original_commit_empty(commit);
1547 if (empty_commit < 0)
1548 return empty_commit;
1549 if (!empty_commit)
1550 return 0;
1551 else
1552 return 1;
1556 * Note that ordering matters in this enum. Not only must it match the mapping
1557 * below, it is also divided into several sections that matter. When adding
1558 * new commands, make sure you add it in the right section.
1560 enum todo_command {
1561 /* commands that handle commits */
1562 TODO_PICK = 0,
1563 TODO_REVERT,
1564 TODO_EDIT,
1565 TODO_REWORD,
1566 TODO_FIXUP,
1567 TODO_SQUASH,
1568 /* commands that do something else than handling a single commit */
1569 TODO_EXEC,
1570 TODO_BREAK,
1571 TODO_LABEL,
1572 TODO_RESET,
1573 TODO_MERGE,
1574 /* commands that do nothing but are counted for reporting progress */
1575 TODO_NOOP,
1576 TODO_DROP,
1577 /* comments (not counted for reporting progress) */
1578 TODO_COMMENT
1581 static struct {
1582 char c;
1583 const char *str;
1584 } todo_command_info[] = {
1585 { 'p', "pick" },
1586 { 0, "revert" },
1587 { 'e', "edit" },
1588 { 'r', "reword" },
1589 { 'f', "fixup" },
1590 { 's', "squash" },
1591 { 'x', "exec" },
1592 { 'b', "break" },
1593 { 'l', "label" },
1594 { 't', "reset" },
1595 { 'm', "merge" },
1596 { 0, "noop" },
1597 { 'd', "drop" },
1598 { 0, NULL }
1601 static const char *command_to_string(const enum todo_command command)
1603 if (command < TODO_COMMENT)
1604 return todo_command_info[command].str;
1605 die(_("unknown command: %d"), command);
1608 static char command_to_char(const enum todo_command command)
1610 if (command < TODO_COMMENT && todo_command_info[command].c)
1611 return todo_command_info[command].c;
1612 return comment_line_char;
1615 static int is_noop(const enum todo_command command)
1617 return TODO_NOOP <= command;
1620 static int is_fixup(enum todo_command command)
1622 return command == TODO_FIXUP || command == TODO_SQUASH;
1625 /* Does this command create a (non-merge) commit? */
1626 static int is_pick_or_similar(enum todo_command command)
1628 switch (command) {
1629 case TODO_PICK:
1630 case TODO_REVERT:
1631 case TODO_EDIT:
1632 case TODO_REWORD:
1633 case TODO_FIXUP:
1634 case TODO_SQUASH:
1635 return 1;
1636 default:
1637 return 0;
1641 static int update_squash_messages(struct repository *r,
1642 enum todo_command command,
1643 struct commit *commit,
1644 struct replay_opts *opts)
1646 struct strbuf buf = STRBUF_INIT;
1647 int res;
1648 const char *message, *body;
1650 if (opts->current_fixup_count > 0) {
1651 struct strbuf header = STRBUF_INIT;
1652 char *eol;
1654 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1655 return error(_("could not read '%s'"),
1656 rebase_path_squash_msg());
1658 eol = buf.buf[0] != comment_line_char ?
1659 buf.buf : strchrnul(buf.buf, '\n');
1661 strbuf_addf(&header, "%c ", comment_line_char);
1662 strbuf_addf(&header, _("This is a combination of %d commits."),
1663 opts->current_fixup_count + 2);
1664 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1665 strbuf_release(&header);
1666 } else {
1667 struct object_id head;
1668 struct commit *head_commit;
1669 const char *head_message, *body;
1671 if (get_oid("HEAD", &head))
1672 return error(_("need a HEAD to fixup"));
1673 if (!(head_commit = lookup_commit_reference(r, &head)))
1674 return error(_("could not read HEAD"));
1675 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1676 return error(_("could not read HEAD's commit message"));
1678 find_commit_subject(head_message, &body);
1679 if (write_message(body, strlen(body),
1680 rebase_path_fixup_msg(), 0)) {
1681 unuse_commit_buffer(head_commit, head_message);
1682 return error(_("cannot write '%s'"),
1683 rebase_path_fixup_msg());
1686 strbuf_addf(&buf, "%c ", comment_line_char);
1687 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1688 strbuf_addf(&buf, "\n%c ", comment_line_char);
1689 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1690 strbuf_addstr(&buf, "\n\n");
1691 strbuf_addstr(&buf, body);
1693 unuse_commit_buffer(head_commit, head_message);
1696 if (!(message = get_commit_buffer(commit, NULL)))
1697 return error(_("could not read commit message of %s"),
1698 oid_to_hex(&commit->object.oid));
1699 find_commit_subject(message, &body);
1701 if (command == TODO_SQUASH) {
1702 unlink(rebase_path_fixup_msg());
1703 strbuf_addf(&buf, "\n%c ", comment_line_char);
1704 strbuf_addf(&buf, _("This is the commit message #%d:"),
1705 ++opts->current_fixup_count + 1);
1706 strbuf_addstr(&buf, "\n\n");
1707 strbuf_addstr(&buf, body);
1708 } else if (command == TODO_FIXUP) {
1709 strbuf_addf(&buf, "\n%c ", comment_line_char);
1710 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1711 ++opts->current_fixup_count + 1);
1712 strbuf_addstr(&buf, "\n\n");
1713 strbuf_add_commented_lines(&buf, body, strlen(body));
1714 } else
1715 return error(_("unknown command: %d"), command);
1716 unuse_commit_buffer(commit, message);
1718 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1719 strbuf_release(&buf);
1721 if (!res) {
1722 strbuf_addf(&opts->current_fixups, "%s%s %s",
1723 opts->current_fixups.len ? "\n" : "",
1724 command_to_string(command),
1725 oid_to_hex(&commit->object.oid));
1726 res = write_message(opts->current_fixups.buf,
1727 opts->current_fixups.len,
1728 rebase_path_current_fixups(), 0);
1731 return res;
1734 static void flush_rewritten_pending(void)
1736 struct strbuf buf = STRBUF_INIT;
1737 struct object_id newoid;
1738 FILE *out;
1740 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1741 !get_oid("HEAD", &newoid) &&
1742 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1743 char *bol = buf.buf, *eol;
1745 while (*bol) {
1746 eol = strchrnul(bol, '\n');
1747 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1748 bol, oid_to_hex(&newoid));
1749 if (!*eol)
1750 break;
1751 bol = eol + 1;
1753 fclose(out);
1754 unlink(rebase_path_rewritten_pending());
1756 strbuf_release(&buf);
1759 static void record_in_rewritten(struct object_id *oid,
1760 enum todo_command next_command)
1762 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1764 if (!out)
1765 return;
1767 fprintf(out, "%s\n", oid_to_hex(oid));
1768 fclose(out);
1770 if (!is_fixup(next_command))
1771 flush_rewritten_pending();
1774 static int do_pick_commit(struct repository *r,
1775 enum todo_command command,
1776 struct commit *commit,
1777 struct replay_opts *opts,
1778 int final_fixup)
1780 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1781 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1782 struct object_id head;
1783 struct commit *base, *next, *parent;
1784 const char *base_label, *next_label;
1785 char *author = NULL;
1786 struct commit_message msg = { NULL, NULL, NULL, NULL };
1787 struct strbuf msgbuf = STRBUF_INIT;
1788 int res, unborn = 0, allow;
1790 if (opts->no_commit) {
1792 * We do not intend to commit immediately. We just want to
1793 * merge the differences in, so let's compute the tree
1794 * that represents the "current" state for merge-recursive
1795 * to work on.
1797 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1798 return error(_("your index file is unmerged."));
1799 } else {
1800 unborn = get_oid("HEAD", &head);
1801 /* Do we want to generate a root commit? */
1802 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1803 oideq(&head, &opts->squash_onto)) {
1804 if (is_fixup(command))
1805 return error(_("cannot fixup root commit"));
1806 flags |= CREATE_ROOT_COMMIT;
1807 unborn = 1;
1808 } else if (unborn)
1809 oidcpy(&head, the_hash_algo->empty_tree);
1810 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1811 NULL, 0))
1812 return error_dirty_index(r, opts);
1814 discard_index(r->index);
1816 if (!commit->parents)
1817 parent = NULL;
1818 else if (commit->parents->next) {
1819 /* Reverting or cherry-picking a merge commit */
1820 int cnt;
1821 struct commit_list *p;
1823 if (!opts->mainline)
1824 return error(_("commit %s is a merge but no -m option was given."),
1825 oid_to_hex(&commit->object.oid));
1827 for (cnt = 1, p = commit->parents;
1828 cnt != opts->mainline && p;
1829 cnt++)
1830 p = p->next;
1831 if (cnt != opts->mainline || !p)
1832 return error(_("commit %s does not have parent %d"),
1833 oid_to_hex(&commit->object.oid), opts->mainline);
1834 parent = p->item;
1835 } else if (1 < opts->mainline)
1837 * Non-first parent explicitly specified as mainline for
1838 * non-merge commit
1840 return error(_("commit %s does not have parent %d"),
1841 oid_to_hex(&commit->object.oid), opts->mainline);
1842 else
1843 parent = commit->parents->item;
1845 if (get_message(commit, &msg) != 0)
1846 return error(_("cannot get commit message for %s"),
1847 oid_to_hex(&commit->object.oid));
1849 if (opts->allow_ff && !is_fixup(command) &&
1850 ((parent && oideq(&parent->object.oid, &head)) ||
1851 (!parent && unborn))) {
1852 if (is_rebase_i(opts))
1853 write_author_script(msg.message);
1854 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1855 opts);
1856 if (res || command != TODO_REWORD)
1857 goto leave;
1858 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1859 msg_file = NULL;
1860 goto fast_forward_edit;
1862 if (parent && parse_commit(parent) < 0)
1863 /* TRANSLATORS: The first %s will be a "todo" command like
1864 "revert" or "pick", the second %s a SHA1. */
1865 return error(_("%s: cannot parse parent commit %s"),
1866 command_to_string(command),
1867 oid_to_hex(&parent->object.oid));
1870 * "commit" is an existing commit. We would want to apply
1871 * the difference it introduces since its first parent "prev"
1872 * on top of the current HEAD if we are cherry-pick. Or the
1873 * reverse of it if we are revert.
1876 if (command == TODO_REVERT) {
1877 base = commit;
1878 base_label = msg.label;
1879 next = parent;
1880 next_label = msg.parent_label;
1881 strbuf_addstr(&msgbuf, "Revert \"");
1882 strbuf_addstr(&msgbuf, msg.subject);
1883 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1884 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1886 if (commit->parents && commit->parents->next) {
1887 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1888 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1890 strbuf_addstr(&msgbuf, ".\n");
1891 } else {
1892 const char *p;
1894 base = parent;
1895 base_label = msg.parent_label;
1896 next = commit;
1897 next_label = msg.label;
1899 /* Append the commit log message to msgbuf. */
1900 if (find_commit_subject(msg.message, &p))
1901 strbuf_addstr(&msgbuf, p);
1903 if (opts->record_origin) {
1904 strbuf_complete_line(&msgbuf);
1905 if (!has_conforming_footer(&msgbuf, NULL, 0))
1906 strbuf_addch(&msgbuf, '\n');
1907 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1908 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1909 strbuf_addstr(&msgbuf, ")\n");
1911 if (!is_fixup(command))
1912 author = get_author(msg.message);
1915 if (command == TODO_REWORD)
1916 flags |= EDIT_MSG | VERIFY_MSG;
1917 else if (is_fixup(command)) {
1918 if (update_squash_messages(r, command, commit, opts))
1919 return -1;
1920 flags |= AMEND_MSG;
1921 if (!final_fixup)
1922 msg_file = rebase_path_squash_msg();
1923 else if (file_exists(rebase_path_fixup_msg())) {
1924 flags |= CLEANUP_MSG;
1925 msg_file = rebase_path_fixup_msg();
1926 } else {
1927 const char *dest = git_path_squash_msg(r);
1928 unlink(dest);
1929 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1930 return error(_("could not rename '%s' to '%s'"),
1931 rebase_path_squash_msg(), dest);
1932 unlink(git_path_merge_msg(r));
1933 msg_file = dest;
1934 flags |= EDIT_MSG;
1938 if (opts->signoff && !is_fixup(command))
1939 append_signoff(&msgbuf, 0, 0);
1941 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1942 res = -1;
1943 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1944 res = do_recursive_merge(r, base, next, base_label, next_label,
1945 &head, &msgbuf, opts);
1946 if (res < 0)
1947 goto leave;
1949 res |= write_message(msgbuf.buf, msgbuf.len,
1950 git_path_merge_msg(r), 0);
1951 } else {
1952 struct commit_list *common = NULL;
1953 struct commit_list *remotes = NULL;
1955 res = write_message(msgbuf.buf, msgbuf.len,
1956 git_path_merge_msg(r), 0);
1958 commit_list_insert(base, &common);
1959 commit_list_insert(next, &remotes);
1960 res |= try_merge_command(r, opts->strategy,
1961 opts->xopts_nr, (const char **)opts->xopts,
1962 common, oid_to_hex(&head), remotes);
1963 free_commit_list(common);
1964 free_commit_list(remotes);
1966 strbuf_release(&msgbuf);
1969 * If the merge was clean or if it failed due to conflict, we write
1970 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1971 * However, if the merge did not even start, then we don't want to
1972 * write it at all.
1974 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1975 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1976 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1977 res = -1;
1978 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1979 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1980 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1981 res = -1;
1983 if (res) {
1984 error(command == TODO_REVERT
1985 ? _("could not revert %s... %s")
1986 : _("could not apply %s... %s"),
1987 short_commit_name(commit), msg.subject);
1988 print_advice(r, res == 1, opts);
1989 repo_rerere(r, opts->allow_rerere_auto);
1990 goto leave;
1993 allow = allow_empty(r, opts, commit);
1994 if (allow < 0) {
1995 res = allow;
1996 goto leave;
1997 } else if (allow)
1998 flags |= ALLOW_EMPTY;
1999 if (!opts->no_commit) {
2000 fast_forward_edit:
2001 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2002 res = do_commit(r, msg_file, author, opts, flags);
2003 else
2004 res = error(_("unable to parse commit author"));
2007 if (!res && final_fixup) {
2008 unlink(rebase_path_fixup_msg());
2009 unlink(rebase_path_squash_msg());
2010 unlink(rebase_path_current_fixups());
2011 strbuf_reset(&opts->current_fixups);
2012 opts->current_fixup_count = 0;
2015 leave:
2016 free_message(commit, &msg);
2017 free(author);
2018 update_abort_safety_file();
2020 return res;
2023 static int prepare_revs(struct replay_opts *opts)
2026 * picking (but not reverting) ranges (but not individual revisions)
2027 * should be done in reverse
2029 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2030 opts->revs->reverse ^= 1;
2032 if (prepare_revision_walk(opts->revs))
2033 return error(_("revision walk setup failed"));
2035 return 0;
2038 static int read_and_refresh_cache(struct repository *r,
2039 struct replay_opts *opts)
2041 struct lock_file index_lock = LOCK_INIT;
2042 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2043 if (repo_read_index(r) < 0) {
2044 rollback_lock_file(&index_lock);
2045 return error(_("git %s: failed to read the index"),
2046 _(action_name(opts)));
2048 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2049 if (index_fd >= 0) {
2050 if (write_locked_index(r->index, &index_lock,
2051 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2052 return error(_("git %s: failed to refresh the index"),
2053 _(action_name(opts)));
2056 return 0;
2059 enum todo_item_flags {
2060 TODO_EDIT_MERGE_MSG = 1
2063 struct todo_item {
2064 enum todo_command command;
2065 struct commit *commit;
2066 unsigned int flags;
2067 const char *arg;
2068 int arg_len;
2069 size_t offset_in_buf;
2072 struct todo_list {
2073 struct strbuf buf;
2074 struct todo_item *items;
2075 int nr, alloc, current;
2076 int done_nr, total_nr;
2077 struct stat_data stat;
2080 #define TODO_LIST_INIT { STRBUF_INIT }
2082 static void todo_list_release(struct todo_list *todo_list)
2084 strbuf_release(&todo_list->buf);
2085 FREE_AND_NULL(todo_list->items);
2086 todo_list->nr = todo_list->alloc = 0;
2089 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2091 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2092 return todo_list->items + todo_list->nr++;
2095 static int parse_insn_line(struct repository *r, struct todo_item *item,
2096 const char *bol, char *eol)
2098 struct object_id commit_oid;
2099 char *end_of_object_name;
2100 int i, saved, status, padding;
2102 item->flags = 0;
2104 /* left-trim */
2105 bol += strspn(bol, " \t");
2107 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2108 item->command = TODO_COMMENT;
2109 item->commit = NULL;
2110 item->arg = bol;
2111 item->arg_len = eol - bol;
2112 return 0;
2115 for (i = 0; i < TODO_COMMENT; i++)
2116 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2117 item->command = i;
2118 break;
2119 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2120 *bol == todo_command_info[i].c) {
2121 bol++;
2122 item->command = i;
2123 break;
2125 if (i >= TODO_COMMENT)
2126 return -1;
2128 /* Eat up extra spaces/ tabs before object name */
2129 padding = strspn(bol, " \t");
2130 bol += padding;
2132 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2133 if (bol != eol)
2134 return error(_("%s does not accept arguments: '%s'"),
2135 command_to_string(item->command), bol);
2136 item->commit = NULL;
2137 item->arg = bol;
2138 item->arg_len = eol - bol;
2139 return 0;
2142 if (!padding)
2143 return error(_("missing arguments for %s"),
2144 command_to_string(item->command));
2146 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2147 item->command == TODO_RESET) {
2148 item->commit = NULL;
2149 item->arg = bol;
2150 item->arg_len = (int)(eol - bol);
2151 return 0;
2154 if (item->command == TODO_MERGE) {
2155 if (skip_prefix(bol, "-C", &bol))
2156 bol += strspn(bol, " \t");
2157 else if (skip_prefix(bol, "-c", &bol)) {
2158 bol += strspn(bol, " \t");
2159 item->flags |= TODO_EDIT_MERGE_MSG;
2160 } else {
2161 item->flags |= TODO_EDIT_MERGE_MSG;
2162 item->commit = NULL;
2163 item->arg = bol;
2164 item->arg_len = (int)(eol - bol);
2165 return 0;
2169 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2170 saved = *end_of_object_name;
2171 *end_of_object_name = '\0';
2172 status = get_oid(bol, &commit_oid);
2173 *end_of_object_name = saved;
2175 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2176 item->arg_len = (int)(eol - item->arg);
2178 if (status < 0)
2179 return error(_("could not parse '%.*s'"),
2180 (int)(end_of_object_name - bol), bol);
2182 item->commit = lookup_commit_reference(r, &commit_oid);
2183 return !item->commit;
2186 static int parse_insn_buffer(struct repository *r, char *buf,
2187 struct todo_list *todo_list)
2189 struct todo_item *item;
2190 char *p = buf, *next_p;
2191 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2193 for (i = 1; *p; i++, p = next_p) {
2194 char *eol = strchrnul(p, '\n');
2196 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2198 if (p != eol && eol[-1] == '\r')
2199 eol--; /* strip Carriage Return */
2201 item = append_new_todo(todo_list);
2202 item->offset_in_buf = p - todo_list->buf.buf;
2203 if (parse_insn_line(r, item, p, eol)) {
2204 res = error(_("invalid line %d: %.*s"),
2205 i, (int)(eol - p), p);
2206 item->command = TODO_NOOP;
2209 if (fixup_okay)
2210 ; /* do nothing */
2211 else if (is_fixup(item->command))
2212 return error(_("cannot '%s' without a previous commit"),
2213 command_to_string(item->command));
2214 else if (!is_noop(item->command))
2215 fixup_okay = 1;
2218 return res;
2221 static int count_commands(struct todo_list *todo_list)
2223 int count = 0, i;
2225 for (i = 0; i < todo_list->nr; i++)
2226 if (todo_list->items[i].command != TODO_COMMENT)
2227 count++;
2229 return count;
2232 static int get_item_line_offset(struct todo_list *todo_list, int index)
2234 return index < todo_list->nr ?
2235 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2238 static const char *get_item_line(struct todo_list *todo_list, int index)
2240 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2243 static int get_item_line_length(struct todo_list *todo_list, int index)
2245 return get_item_line_offset(todo_list, index + 1)
2246 - get_item_line_offset(todo_list, index);
2249 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2251 int fd;
2252 ssize_t len;
2254 fd = open(path, O_RDONLY);
2255 if (fd < 0)
2256 return error_errno(_("could not open '%s'"), path);
2257 len = strbuf_read(sb, fd, 0);
2258 close(fd);
2259 if (len < 0)
2260 return error(_("could not read '%s'."), path);
2261 return len;
2264 static int read_populate_todo(struct repository *r,
2265 struct todo_list *todo_list,
2266 struct replay_opts *opts)
2268 struct stat st;
2269 const char *todo_file = get_todo_path(opts);
2270 int res;
2272 strbuf_reset(&todo_list->buf);
2273 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2274 return -1;
2276 res = stat(todo_file, &st);
2277 if (res)
2278 return error(_("could not stat '%s'"), todo_file);
2279 fill_stat_data(&todo_list->stat, &st);
2281 res = parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2282 if (res) {
2283 if (is_rebase_i(opts))
2284 return error(_("please fix this using "
2285 "'git rebase --edit-todo'."));
2286 return error(_("unusable instruction sheet: '%s'"), todo_file);
2289 if (!todo_list->nr &&
2290 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2291 return error(_("no commits parsed."));
2293 if (!is_rebase_i(opts)) {
2294 enum todo_command valid =
2295 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2296 int i;
2298 for (i = 0; i < todo_list->nr; i++)
2299 if (valid == todo_list->items[i].command)
2300 continue;
2301 else if (valid == TODO_PICK)
2302 return error(_("cannot cherry-pick during a revert."));
2303 else
2304 return error(_("cannot revert during a cherry-pick."));
2307 if (is_rebase_i(opts)) {
2308 struct todo_list done = TODO_LIST_INIT;
2309 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2311 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2312 !parse_insn_buffer(r, done.buf.buf, &done))
2313 todo_list->done_nr = count_commands(&done);
2314 else
2315 todo_list->done_nr = 0;
2317 todo_list->total_nr = todo_list->done_nr
2318 + count_commands(todo_list);
2319 todo_list_release(&done);
2321 if (f) {
2322 fprintf(f, "%d\n", todo_list->total_nr);
2323 fclose(f);
2327 return 0;
2330 static int git_config_string_dup(char **dest,
2331 const char *var, const char *value)
2333 if (!value)
2334 return config_error_nonbool(var);
2335 free(*dest);
2336 *dest = xstrdup(value);
2337 return 0;
2340 static int populate_opts_cb(const char *key, const char *value, void *data)
2342 struct replay_opts *opts = data;
2343 int error_flag = 1;
2345 if (!value)
2346 error_flag = 0;
2347 else if (!strcmp(key, "options.no-commit"))
2348 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2349 else if (!strcmp(key, "options.edit"))
2350 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2351 else if (!strcmp(key, "options.signoff"))
2352 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2353 else if (!strcmp(key, "options.record-origin"))
2354 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2355 else if (!strcmp(key, "options.allow-ff"))
2356 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2357 else if (!strcmp(key, "options.mainline"))
2358 opts->mainline = git_config_int(key, value);
2359 else if (!strcmp(key, "options.strategy"))
2360 git_config_string_dup(&opts->strategy, key, value);
2361 else if (!strcmp(key, "options.gpg-sign"))
2362 git_config_string_dup(&opts->gpg_sign, key, value);
2363 else if (!strcmp(key, "options.strategy-option")) {
2364 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2365 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2366 } else if (!strcmp(key, "options.allow-rerere-auto"))
2367 opts->allow_rerere_auto =
2368 git_config_bool_or_int(key, value, &error_flag) ?
2369 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2370 else
2371 return error(_("invalid key: %s"), key);
2373 if (!error_flag)
2374 return error(_("invalid value for %s: %s"), key, value);
2376 return 0;
2379 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2381 int i;
2382 char *strategy_opts_string = raw_opts;
2384 if (*strategy_opts_string == ' ')
2385 strategy_opts_string++;
2387 opts->xopts_nr = split_cmdline(strategy_opts_string,
2388 (const char ***)&opts->xopts);
2389 for (i = 0; i < opts->xopts_nr; i++) {
2390 const char *arg = opts->xopts[i];
2392 skip_prefix(arg, "--", &arg);
2393 opts->xopts[i] = xstrdup(arg);
2397 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2399 strbuf_reset(buf);
2400 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2401 return;
2402 opts->strategy = strbuf_detach(buf, NULL);
2403 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2404 return;
2406 parse_strategy_opts(opts, buf->buf);
2409 static int read_populate_opts(struct replay_opts *opts)
2411 if (is_rebase_i(opts)) {
2412 struct strbuf buf = STRBUF_INIT;
2414 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2415 if (!starts_with(buf.buf, "-S"))
2416 strbuf_reset(&buf);
2417 else {
2418 free(opts->gpg_sign);
2419 opts->gpg_sign = xstrdup(buf.buf + 2);
2421 strbuf_reset(&buf);
2424 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2425 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2426 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2427 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2428 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2429 strbuf_reset(&buf);
2432 if (file_exists(rebase_path_verbose()))
2433 opts->verbose = 1;
2435 if (file_exists(rebase_path_quiet()))
2436 opts->quiet = 1;
2438 if (file_exists(rebase_path_signoff())) {
2439 opts->allow_ff = 0;
2440 opts->signoff = 1;
2443 if (file_exists(rebase_path_reschedule_failed_exec()))
2444 opts->reschedule_failed_exec = 1;
2446 read_strategy_opts(opts, &buf);
2447 strbuf_release(&buf);
2449 if (read_oneliner(&opts->current_fixups,
2450 rebase_path_current_fixups(), 1)) {
2451 const char *p = opts->current_fixups.buf;
2452 opts->current_fixup_count = 1;
2453 while ((p = strchr(p, '\n'))) {
2454 opts->current_fixup_count++;
2455 p++;
2459 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2460 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2461 return error(_("unusable squash-onto"));
2462 opts->have_squash_onto = 1;
2465 return 0;
2468 if (!file_exists(git_path_opts_file()))
2469 return 0;
2471 * The function git_parse_source(), called from git_config_from_file(),
2472 * may die() in case of a syntactically incorrect file. We do not care
2473 * about this case, though, because we wrote that file ourselves, so we
2474 * are pretty certain that it is syntactically correct.
2476 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2477 return error(_("malformed options sheet: '%s'"),
2478 git_path_opts_file());
2479 return 0;
2482 static void write_strategy_opts(struct replay_opts *opts)
2484 int i;
2485 struct strbuf buf = STRBUF_INIT;
2487 for (i = 0; i < opts->xopts_nr; ++i)
2488 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2490 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2491 strbuf_release(&buf);
2494 int write_basic_state(struct replay_opts *opts, const char *head_name,
2495 const char *onto, const char *orig_head)
2497 const char *quiet = getenv("GIT_QUIET");
2499 if (head_name)
2500 write_file(rebase_path_head_name(), "%s\n", head_name);
2501 if (onto)
2502 write_file(rebase_path_onto(), "%s\n", onto);
2503 if (orig_head)
2504 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2506 if (quiet)
2507 write_file(rebase_path_quiet(), "%s\n", quiet);
2508 if (opts->verbose)
2509 write_file(rebase_path_verbose(), "%s", "");
2510 if (opts->strategy)
2511 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2512 if (opts->xopts_nr > 0)
2513 write_strategy_opts(opts);
2515 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2516 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2517 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2518 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2520 if (opts->gpg_sign)
2521 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2522 if (opts->signoff)
2523 write_file(rebase_path_signoff(), "--signoff\n");
2524 if (opts->reschedule_failed_exec)
2525 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2527 return 0;
2530 static int walk_revs_populate_todo(struct todo_list *todo_list,
2531 struct replay_opts *opts)
2533 enum todo_command command = opts->action == REPLAY_PICK ?
2534 TODO_PICK : TODO_REVERT;
2535 const char *command_string = todo_command_info[command].str;
2536 struct commit *commit;
2538 if (prepare_revs(opts))
2539 return -1;
2541 while ((commit = get_revision(opts->revs))) {
2542 struct todo_item *item = append_new_todo(todo_list);
2543 const char *commit_buffer = get_commit_buffer(commit, NULL);
2544 const char *subject;
2545 int subject_len;
2547 item->command = command;
2548 item->commit = commit;
2549 item->arg = NULL;
2550 item->arg_len = 0;
2551 item->offset_in_buf = todo_list->buf.len;
2552 subject_len = find_commit_subject(commit_buffer, &subject);
2553 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2554 short_commit_name(commit), subject_len, subject);
2555 unuse_commit_buffer(commit, commit_buffer);
2558 if (!todo_list->nr)
2559 return error(_("empty commit set passed"));
2561 return 0;
2564 static int create_seq_dir(void)
2566 if (file_exists(git_path_seq_dir())) {
2567 error(_("a cherry-pick or revert is already in progress"));
2568 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2569 return -1;
2570 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2571 return error_errno(_("could not create sequencer directory '%s'"),
2572 git_path_seq_dir());
2573 return 0;
2576 static int save_head(const char *head)
2578 struct lock_file head_lock = LOCK_INIT;
2579 struct strbuf buf = STRBUF_INIT;
2580 int fd;
2581 ssize_t written;
2583 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2584 if (fd < 0)
2585 return error_errno(_("could not lock HEAD"));
2586 strbuf_addf(&buf, "%s\n", head);
2587 written = write_in_full(fd, buf.buf, buf.len);
2588 strbuf_release(&buf);
2589 if (written < 0) {
2590 error_errno(_("could not write to '%s'"), git_path_head_file());
2591 rollback_lock_file(&head_lock);
2592 return -1;
2594 if (commit_lock_file(&head_lock) < 0)
2595 return error(_("failed to finalize '%s'"), git_path_head_file());
2596 return 0;
2599 static int rollback_is_safe(void)
2601 struct strbuf sb = STRBUF_INIT;
2602 struct object_id expected_head, actual_head;
2604 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2605 strbuf_trim(&sb);
2606 if (get_oid_hex(sb.buf, &expected_head)) {
2607 strbuf_release(&sb);
2608 die(_("could not parse %s"), git_path_abort_safety_file());
2610 strbuf_release(&sb);
2612 else if (errno == ENOENT)
2613 oidclr(&expected_head);
2614 else
2615 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2617 if (get_oid("HEAD", &actual_head))
2618 oidclr(&actual_head);
2620 return oideq(&actual_head, &expected_head);
2623 static int reset_for_rollback(const struct object_id *oid)
2625 const char *argv[4]; /* reset --merge <arg> + NULL */
2627 argv[0] = "reset";
2628 argv[1] = "--merge";
2629 argv[2] = oid_to_hex(oid);
2630 argv[3] = NULL;
2631 return run_command_v_opt(argv, RUN_GIT_CMD);
2634 static int rollback_single_pick(struct repository *r)
2636 struct object_id head_oid;
2638 if (!file_exists(git_path_cherry_pick_head(r)) &&
2639 !file_exists(git_path_revert_head(r)))
2640 return error(_("no cherry-pick or revert in progress"));
2641 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2642 return error(_("cannot resolve HEAD"));
2643 if (is_null_oid(&head_oid))
2644 return error(_("cannot abort from a branch yet to be born"));
2645 return reset_for_rollback(&head_oid);
2648 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2650 FILE *f;
2651 struct object_id oid;
2652 struct strbuf buf = STRBUF_INIT;
2653 const char *p;
2655 f = fopen(git_path_head_file(), "r");
2656 if (!f && errno == ENOENT) {
2658 * There is no multiple-cherry-pick in progress.
2659 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2660 * a single-cherry-pick in progress, abort that.
2662 return rollback_single_pick(r);
2664 if (!f)
2665 return error_errno(_("cannot open '%s'"), git_path_head_file());
2666 if (strbuf_getline_lf(&buf, f)) {
2667 error(_("cannot read '%s': %s"), git_path_head_file(),
2668 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2669 fclose(f);
2670 goto fail;
2672 fclose(f);
2673 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2674 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2675 git_path_head_file());
2676 goto fail;
2678 if (is_null_oid(&oid)) {
2679 error(_("cannot abort from a branch yet to be born"));
2680 goto fail;
2683 if (!rollback_is_safe()) {
2684 /* Do not error, just do not rollback */
2685 warning(_("You seem to have moved HEAD. "
2686 "Not rewinding, check your HEAD!"));
2687 } else
2688 if (reset_for_rollback(&oid))
2689 goto fail;
2690 strbuf_release(&buf);
2691 return sequencer_remove_state(opts);
2692 fail:
2693 strbuf_release(&buf);
2694 return -1;
2697 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2699 struct lock_file todo_lock = LOCK_INIT;
2700 const char *todo_path = get_todo_path(opts);
2701 int next = todo_list->current, offset, fd;
2704 * rebase -i writes "git-rebase-todo" without the currently executing
2705 * command, appending it to "done" instead.
2707 if (is_rebase_i(opts))
2708 next++;
2710 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2711 if (fd < 0)
2712 return error_errno(_("could not lock '%s'"), todo_path);
2713 offset = get_item_line_offset(todo_list, next);
2714 if (write_in_full(fd, todo_list->buf.buf + offset,
2715 todo_list->buf.len - offset) < 0)
2716 return error_errno(_("could not write to '%s'"), todo_path);
2717 if (commit_lock_file(&todo_lock) < 0)
2718 return error(_("failed to finalize '%s'"), todo_path);
2720 if (is_rebase_i(opts) && next > 0) {
2721 const char *done = rebase_path_done();
2722 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2723 int ret = 0;
2725 if (fd < 0)
2726 return 0;
2727 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2728 get_item_line_length(todo_list, next - 1))
2729 < 0)
2730 ret = error_errno(_("could not write to '%s'"), done);
2731 if (close(fd) < 0)
2732 ret = error_errno(_("failed to finalize '%s'"), done);
2733 return ret;
2735 return 0;
2738 static int save_opts(struct replay_opts *opts)
2740 const char *opts_file = git_path_opts_file();
2741 int res = 0;
2743 if (opts->no_commit)
2744 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2745 if (opts->edit)
2746 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2747 if (opts->signoff)
2748 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2749 if (opts->record_origin)
2750 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2751 if (opts->allow_ff)
2752 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2753 if (opts->mainline) {
2754 struct strbuf buf = STRBUF_INIT;
2755 strbuf_addf(&buf, "%d", opts->mainline);
2756 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2757 strbuf_release(&buf);
2759 if (opts->strategy)
2760 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2761 if (opts->gpg_sign)
2762 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2763 if (opts->xopts) {
2764 int i;
2765 for (i = 0; i < opts->xopts_nr; i++)
2766 res |= git_config_set_multivar_in_file_gently(opts_file,
2767 "options.strategy-option",
2768 opts->xopts[i], "^$", 0);
2770 if (opts->allow_rerere_auto)
2771 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2772 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2773 "true" : "false");
2774 return res;
2777 static int make_patch(struct repository *r,
2778 struct commit *commit,
2779 struct replay_opts *opts)
2781 struct strbuf buf = STRBUF_INIT;
2782 struct rev_info log_tree_opt;
2783 const char *subject, *p;
2784 int res = 0;
2786 p = short_commit_name(commit);
2787 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2788 return -1;
2789 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2790 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2791 res |= error(_("could not update %s"), "REBASE_HEAD");
2793 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2794 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2795 repo_init_revisions(r, &log_tree_opt, NULL);
2796 log_tree_opt.abbrev = 0;
2797 log_tree_opt.diff = 1;
2798 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2799 log_tree_opt.disable_stdin = 1;
2800 log_tree_opt.no_commit_id = 1;
2801 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2802 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2803 if (!log_tree_opt.diffopt.file)
2804 res |= error_errno(_("could not open '%s'"), buf.buf);
2805 else {
2806 res |= log_tree_commit(&log_tree_opt, commit);
2807 fclose(log_tree_opt.diffopt.file);
2809 strbuf_reset(&buf);
2811 strbuf_addf(&buf, "%s/message", get_dir(opts));
2812 if (!file_exists(buf.buf)) {
2813 const char *commit_buffer = get_commit_buffer(commit, NULL);
2814 find_commit_subject(commit_buffer, &subject);
2815 res |= write_message(subject, strlen(subject), buf.buf, 1);
2816 unuse_commit_buffer(commit, commit_buffer);
2818 strbuf_release(&buf);
2820 return res;
2823 static int intend_to_amend(void)
2825 struct object_id head;
2826 char *p;
2828 if (get_oid("HEAD", &head))
2829 return error(_("cannot read HEAD"));
2831 p = oid_to_hex(&head);
2832 return write_message(p, strlen(p), rebase_path_amend(), 1);
2835 static int error_with_patch(struct repository *r,
2836 struct commit *commit,
2837 const char *subject, int subject_len,
2838 struct replay_opts *opts,
2839 int exit_code, int to_amend)
2841 if (commit) {
2842 if (make_patch(r, commit, opts))
2843 return -1;
2844 } else if (copy_file(rebase_path_message(),
2845 git_path_merge_msg(r), 0666))
2846 return error(_("unable to copy '%s' to '%s'"),
2847 git_path_merge_msg(r), rebase_path_message());
2849 if (to_amend) {
2850 if (intend_to_amend())
2851 return -1;
2853 fprintf(stderr,
2854 _("You can amend the commit now, with\n"
2855 "\n"
2856 " git commit --amend %s\n"
2857 "\n"
2858 "Once you are satisfied with your changes, run\n"
2859 "\n"
2860 " git rebase --continue\n"),
2861 gpg_sign_opt_quoted(opts));
2862 } else if (exit_code) {
2863 if (commit)
2864 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2865 short_commit_name(commit), subject_len, subject);
2866 else
2868 * We don't have the hash of the parent so
2869 * just print the line from the todo file.
2871 fprintf_ln(stderr, _("Could not merge %.*s"),
2872 subject_len, subject);
2875 return exit_code;
2878 static int error_failed_squash(struct repository *r,
2879 struct commit *commit,
2880 struct replay_opts *opts,
2881 int subject_len,
2882 const char *subject)
2884 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2885 return error(_("could not copy '%s' to '%s'"),
2886 rebase_path_squash_msg(), rebase_path_message());
2887 unlink(git_path_merge_msg(r));
2888 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
2889 return error(_("could not copy '%s' to '%s'"),
2890 rebase_path_message(),
2891 git_path_merge_msg(r));
2892 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
2895 static int do_exec(struct repository *r, const char *command_line)
2897 struct argv_array child_env = ARGV_ARRAY_INIT;
2898 const char *child_argv[] = { NULL, NULL };
2899 int dirty, status;
2901 fprintf(stderr, "Executing: %s\n", command_line);
2902 child_argv[0] = command_line;
2903 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2904 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2905 absolute_path(get_git_work_tree()));
2906 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2907 child_env.argv);
2909 /* force re-reading of the cache */
2910 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
2911 return error(_("could not read index"));
2913 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
2915 if (status) {
2916 warning(_("execution failed: %s\n%s"
2917 "You can fix the problem, and then run\n"
2918 "\n"
2919 " git rebase --continue\n"
2920 "\n"),
2921 command_line,
2922 dirty ? N_("and made changes to the index and/or the "
2923 "working tree\n") : "");
2924 if (status == 127)
2925 /* command not found */
2926 status = 1;
2927 } else if (dirty) {
2928 warning(_("execution succeeded: %s\nbut "
2929 "left changes to the index and/or the working tree\n"
2930 "Commit or stash your changes, and then run\n"
2931 "\n"
2932 " git rebase --continue\n"
2933 "\n"), command_line);
2934 status = 1;
2937 argv_array_clear(&child_env);
2939 return status;
2942 static int safe_append(const char *filename, const char *fmt, ...)
2944 va_list ap;
2945 struct lock_file lock = LOCK_INIT;
2946 int fd = hold_lock_file_for_update(&lock, filename,
2947 LOCK_REPORT_ON_ERROR);
2948 struct strbuf buf = STRBUF_INIT;
2950 if (fd < 0)
2951 return -1;
2953 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2954 error_errno(_("could not read '%s'"), filename);
2955 rollback_lock_file(&lock);
2956 return -1;
2958 strbuf_complete(&buf, '\n');
2959 va_start(ap, fmt);
2960 strbuf_vaddf(&buf, fmt, ap);
2961 va_end(ap);
2963 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2964 error_errno(_("could not write to '%s'"), filename);
2965 strbuf_release(&buf);
2966 rollback_lock_file(&lock);
2967 return -1;
2969 if (commit_lock_file(&lock) < 0) {
2970 strbuf_release(&buf);
2971 rollback_lock_file(&lock);
2972 return error(_("failed to finalize '%s'"), filename);
2975 strbuf_release(&buf);
2976 return 0;
2979 static int do_label(struct repository *r, const char *name, int len)
2981 struct ref_store *refs = get_main_ref_store(r);
2982 struct ref_transaction *transaction;
2983 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2984 struct strbuf msg = STRBUF_INIT;
2985 int ret = 0;
2986 struct object_id head_oid;
2988 if (len == 1 && *name == '#')
2989 return error(_("illegal label name: '%.*s'"), len, name);
2991 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2992 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2994 transaction = ref_store_transaction_begin(refs, &err);
2995 if (!transaction) {
2996 error("%s", err.buf);
2997 ret = -1;
2998 } else if (get_oid("HEAD", &head_oid)) {
2999 error(_("could not read HEAD"));
3000 ret = -1;
3001 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3002 NULL, 0, msg.buf, &err) < 0 ||
3003 ref_transaction_commit(transaction, &err)) {
3004 error("%s", err.buf);
3005 ret = -1;
3007 ref_transaction_free(transaction);
3008 strbuf_release(&err);
3009 strbuf_release(&msg);
3011 if (!ret)
3012 ret = safe_append(rebase_path_refs_to_delete(),
3013 "%s\n", ref_name.buf);
3014 strbuf_release(&ref_name);
3016 return ret;
3019 static const char *reflog_message(struct replay_opts *opts,
3020 const char *sub_action, const char *fmt, ...);
3022 static int do_reset(struct repository *r,
3023 const char *name, int len,
3024 struct replay_opts *opts)
3026 struct strbuf ref_name = STRBUF_INIT;
3027 struct object_id oid;
3028 struct lock_file lock = LOCK_INIT;
3029 struct tree_desc desc;
3030 struct tree *tree;
3031 struct unpack_trees_options unpack_tree_opts;
3032 int ret = 0;
3034 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3035 return -1;
3037 if (len == 10 && !strncmp("[new root]", name, len)) {
3038 if (!opts->have_squash_onto) {
3039 const char *hex;
3040 if (commit_tree("", 0, the_hash_algo->empty_tree,
3041 NULL, &opts->squash_onto,
3042 NULL, NULL))
3043 return error(_("writing fake root commit"));
3044 opts->have_squash_onto = 1;
3045 hex = oid_to_hex(&opts->squash_onto);
3046 if (write_message(hex, strlen(hex),
3047 rebase_path_squash_onto(), 0))
3048 return error(_("writing squash-onto"));
3050 oidcpy(&oid, &opts->squash_onto);
3051 } else {
3052 int i;
3054 /* Determine the length of the label */
3055 for (i = 0; i < len; i++)
3056 if (isspace(name[i]))
3057 break;
3058 len = i;
3060 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3061 if (get_oid(ref_name.buf, &oid) &&
3062 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3063 error(_("could not read '%s'"), ref_name.buf);
3064 rollback_lock_file(&lock);
3065 strbuf_release(&ref_name);
3066 return -1;
3070 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3071 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3072 unpack_tree_opts.head_idx = 1;
3073 unpack_tree_opts.src_index = r->index;
3074 unpack_tree_opts.dst_index = r->index;
3075 unpack_tree_opts.fn = oneway_merge;
3076 unpack_tree_opts.merge = 1;
3077 unpack_tree_opts.update = 1;
3079 if (repo_read_index_unmerged(r)) {
3080 rollback_lock_file(&lock);
3081 strbuf_release(&ref_name);
3082 return error_resolve_conflict(_(action_name(opts)));
3085 if (!fill_tree_descriptor(&desc, &oid)) {
3086 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3087 rollback_lock_file(&lock);
3088 free((void *)desc.buffer);
3089 strbuf_release(&ref_name);
3090 return -1;
3093 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3094 rollback_lock_file(&lock);
3095 free((void *)desc.buffer);
3096 strbuf_release(&ref_name);
3097 return -1;
3100 tree = parse_tree_indirect(&oid);
3101 prime_cache_tree(r, r->index, tree);
3103 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3104 ret = error(_("could not write index"));
3105 free((void *)desc.buffer);
3107 if (!ret)
3108 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3109 len, name), "HEAD", &oid,
3110 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3112 strbuf_release(&ref_name);
3113 return ret;
3116 static struct commit *lookup_label(const char *label, int len,
3117 struct strbuf *buf)
3119 struct commit *commit;
3121 strbuf_reset(buf);
3122 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3123 commit = lookup_commit_reference_by_name(buf->buf);
3124 if (!commit) {
3125 /* fall back to non-rewritten ref or commit */
3126 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3127 commit = lookup_commit_reference_by_name(buf->buf);
3130 if (!commit)
3131 error(_("could not resolve '%s'"), buf->buf);
3133 return commit;
3136 static int do_merge(struct repository *r,
3137 struct commit *commit,
3138 const char *arg, int arg_len,
3139 int flags, struct replay_opts *opts)
3141 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3142 EDIT_MSG | VERIFY_MSG : 0;
3143 struct strbuf ref_name = STRBUF_INIT;
3144 struct commit *head_commit, *merge_commit, *i;
3145 struct commit_list *bases, *j, *reversed = NULL;
3146 struct commit_list *to_merge = NULL, **tail = &to_merge;
3147 struct merge_options o;
3148 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3149 static struct lock_file lock;
3150 const char *p;
3152 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3153 ret = -1;
3154 goto leave_merge;
3157 head_commit = lookup_commit_reference_by_name("HEAD");
3158 if (!head_commit) {
3159 ret = error(_("cannot merge without a current revision"));
3160 goto leave_merge;
3164 * For octopus merges, the arg starts with the list of revisions to be
3165 * merged. The list is optionally followed by '#' and the oneline.
3167 merge_arg_len = oneline_offset = arg_len;
3168 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3169 if (!*p)
3170 break;
3171 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3172 p += 1 + strspn(p + 1, " \t\n");
3173 oneline_offset = p - arg;
3174 break;
3176 k = strcspn(p, " \t\n");
3177 if (!k)
3178 continue;
3179 merge_commit = lookup_label(p, k, &ref_name);
3180 if (!merge_commit) {
3181 ret = error(_("unable to parse '%.*s'"), k, p);
3182 goto leave_merge;
3184 tail = &commit_list_insert(merge_commit, tail)->next;
3185 p += k;
3186 merge_arg_len = p - arg;
3189 if (!to_merge) {
3190 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3191 goto leave_merge;
3194 if (opts->have_squash_onto &&
3195 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3197 * When the user tells us to "merge" something into a
3198 * "[new root]", let's simply fast-forward to the merge head.
3200 rollback_lock_file(&lock);
3201 if (to_merge->next)
3202 ret = error(_("octopus merge cannot be executed on "
3203 "top of a [new root]"));
3204 else
3205 ret = fast_forward_to(r, &to_merge->item->object.oid,
3206 &head_commit->object.oid, 0,
3207 opts);
3208 goto leave_merge;
3211 if (commit) {
3212 const char *message = get_commit_buffer(commit, NULL);
3213 const char *body;
3214 int len;
3216 if (!message) {
3217 ret = error(_("could not get commit message of '%s'"),
3218 oid_to_hex(&commit->object.oid));
3219 goto leave_merge;
3221 write_author_script(message);
3222 find_commit_subject(message, &body);
3223 len = strlen(body);
3224 ret = write_message(body, len, git_path_merge_msg(r), 0);
3225 unuse_commit_buffer(commit, message);
3226 if (ret) {
3227 error_errno(_("could not write '%s'"),
3228 git_path_merge_msg(r));
3229 goto leave_merge;
3231 } else {
3232 struct strbuf buf = STRBUF_INIT;
3233 int len;
3235 strbuf_addf(&buf, "author %s", git_author_info(0));
3236 write_author_script(buf.buf);
3237 strbuf_reset(&buf);
3239 if (oneline_offset < arg_len) {
3240 p = arg + oneline_offset;
3241 len = arg_len - oneline_offset;
3242 } else {
3243 strbuf_addf(&buf, "Merge %s '%.*s'",
3244 to_merge->next ? "branches" : "branch",
3245 merge_arg_len, arg);
3246 p = buf.buf;
3247 len = buf.len;
3250 ret = write_message(p, len, git_path_merge_msg(r), 0);
3251 strbuf_release(&buf);
3252 if (ret) {
3253 error_errno(_("could not write '%s'"),
3254 git_path_merge_msg(r));
3255 goto leave_merge;
3260 * If HEAD is not identical to the first parent of the original merge
3261 * commit, we cannot fast-forward.
3263 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3264 oideq(&commit->parents->item->object.oid,
3265 &head_commit->object.oid);
3268 * If any merge head is different from the original one, we cannot
3269 * fast-forward.
3271 if (can_fast_forward) {
3272 struct commit_list *p = commit->parents->next;
3274 for (j = to_merge; j && p; j = j->next, p = p->next)
3275 if (!oideq(&j->item->object.oid,
3276 &p->item->object.oid)) {
3277 can_fast_forward = 0;
3278 break;
3281 * If the number of merge heads differs from the original merge
3282 * commit, we cannot fast-forward.
3284 if (j || p)
3285 can_fast_forward = 0;
3288 if (can_fast_forward) {
3289 rollback_lock_file(&lock);
3290 ret = fast_forward_to(r, &commit->object.oid,
3291 &head_commit->object.oid, 0, opts);
3292 goto leave_merge;
3295 if (to_merge->next) {
3296 /* Octopus merge */
3297 struct child_process cmd = CHILD_PROCESS_INIT;
3299 if (read_env_script(&cmd.env_array)) {
3300 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3302 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3303 goto leave_merge;
3306 cmd.git_cmd = 1;
3307 argv_array_push(&cmd.args, "merge");
3308 argv_array_push(&cmd.args, "-s");
3309 argv_array_push(&cmd.args, "octopus");
3310 argv_array_push(&cmd.args, "--no-edit");
3311 argv_array_push(&cmd.args, "--no-ff");
3312 argv_array_push(&cmd.args, "--no-log");
3313 argv_array_push(&cmd.args, "--no-stat");
3314 argv_array_push(&cmd.args, "-F");
3315 argv_array_push(&cmd.args, git_path_merge_msg(r));
3316 if (opts->gpg_sign)
3317 argv_array_push(&cmd.args, opts->gpg_sign);
3319 /* Add the tips to be merged */
3320 for (j = to_merge; j; j = j->next)
3321 argv_array_push(&cmd.args,
3322 oid_to_hex(&j->item->object.oid));
3324 strbuf_release(&ref_name);
3325 unlink(git_path_cherry_pick_head(r));
3326 rollback_lock_file(&lock);
3328 rollback_lock_file(&lock);
3329 ret = run_command(&cmd);
3331 /* force re-reading of the cache */
3332 if (!ret && (discard_index(r->index) < 0 ||
3333 repo_read_index(r) < 0))
3334 ret = error(_("could not read index"));
3335 goto leave_merge;
3338 merge_commit = to_merge->item;
3339 bases = get_merge_bases(head_commit, merge_commit);
3340 if (bases && oideq(&merge_commit->object.oid,
3341 &bases->item->object.oid)) {
3342 ret = 0;
3343 /* skip merging an ancestor of HEAD */
3344 goto leave_merge;
3347 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3348 git_path_merge_head(r), 0);
3349 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3351 for (j = bases; j; j = j->next)
3352 commit_list_insert(j->item, &reversed);
3353 free_commit_list(bases);
3355 repo_read_index(r);
3356 init_merge_options(&o, r);
3357 o.branch1 = "HEAD";
3358 o.branch2 = ref_name.buf;
3359 o.buffer_output = 2;
3361 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3362 if (ret <= 0)
3363 fputs(o.obuf.buf, stdout);
3364 strbuf_release(&o.obuf);
3365 if (ret < 0) {
3366 error(_("could not even attempt to merge '%.*s'"),
3367 merge_arg_len, arg);
3368 goto leave_merge;
3371 * The return value of merge_recursive() is 1 on clean, and 0 on
3372 * unclean merge.
3374 * Let's reverse that, so that do_merge() returns 0 upon success and
3375 * 1 upon failed merge (keeping the return value -1 for the cases where
3376 * we will want to reschedule the `merge` command).
3378 ret = !ret;
3380 if (r->index->cache_changed &&
3381 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3382 ret = error(_("merge: Unable to write new index file"));
3383 goto leave_merge;
3386 rollback_lock_file(&lock);
3387 if (ret)
3388 repo_rerere(r, opts->allow_rerere_auto);
3389 else
3391 * In case of problems, we now want to return a positive
3392 * value (a negative one would indicate that the `merge`
3393 * command needs to be rescheduled).
3395 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3396 run_commit_flags);
3398 leave_merge:
3399 strbuf_release(&ref_name);
3400 rollback_lock_file(&lock);
3401 free_commit_list(to_merge);
3402 return ret;
3405 static int is_final_fixup(struct todo_list *todo_list)
3407 int i = todo_list->current;
3409 if (!is_fixup(todo_list->items[i].command))
3410 return 0;
3412 while (++i < todo_list->nr)
3413 if (is_fixup(todo_list->items[i].command))
3414 return 0;
3415 else if (!is_noop(todo_list->items[i].command))
3416 break;
3417 return 1;
3420 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3422 int i;
3424 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3425 if (!is_noop(todo_list->items[i].command))
3426 return todo_list->items[i].command;
3428 return -1;
3431 static int apply_autostash(struct replay_opts *opts)
3433 struct strbuf stash_sha1 = STRBUF_INIT;
3434 struct child_process child = CHILD_PROCESS_INIT;
3435 int ret = 0;
3437 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3438 strbuf_release(&stash_sha1);
3439 return 0;
3441 strbuf_trim(&stash_sha1);
3443 child.git_cmd = 1;
3444 child.no_stdout = 1;
3445 child.no_stderr = 1;
3446 argv_array_push(&child.args, "stash");
3447 argv_array_push(&child.args, "apply");
3448 argv_array_push(&child.args, stash_sha1.buf);
3449 if (!run_command(&child))
3450 fprintf(stderr, _("Applied autostash.\n"));
3451 else {
3452 struct child_process store = CHILD_PROCESS_INIT;
3454 store.git_cmd = 1;
3455 argv_array_push(&store.args, "stash");
3456 argv_array_push(&store.args, "store");
3457 argv_array_push(&store.args, "-m");
3458 argv_array_push(&store.args, "autostash");
3459 argv_array_push(&store.args, "-q");
3460 argv_array_push(&store.args, stash_sha1.buf);
3461 if (run_command(&store))
3462 ret = error(_("cannot store %s"), stash_sha1.buf);
3463 else
3464 fprintf(stderr,
3465 _("Applying autostash resulted in conflicts.\n"
3466 "Your changes are safe in the stash.\n"
3467 "You can run \"git stash pop\" or"
3468 " \"git stash drop\" at any time.\n"));
3471 strbuf_release(&stash_sha1);
3472 return ret;
3475 static const char *reflog_message(struct replay_opts *opts,
3476 const char *sub_action, const char *fmt, ...)
3478 va_list ap;
3479 static struct strbuf buf = STRBUF_INIT;
3481 va_start(ap, fmt);
3482 strbuf_reset(&buf);
3483 strbuf_addstr(&buf, action_name(opts));
3484 if (sub_action)
3485 strbuf_addf(&buf, " (%s)", sub_action);
3486 if (fmt) {
3487 strbuf_addstr(&buf, ": ");
3488 strbuf_vaddf(&buf, fmt, ap);
3490 va_end(ap);
3492 return buf.buf;
3495 static int run_git_checkout(struct replay_opts *opts, const char *commit,
3496 const char *action)
3498 struct child_process cmd = CHILD_PROCESS_INIT;
3500 cmd.git_cmd = 1;
3502 argv_array_push(&cmd.args, "checkout");
3503 argv_array_push(&cmd.args, commit);
3504 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3506 if (opts->verbose)
3507 return run_command(&cmd);
3508 else
3509 return run_command_silent_on_success(&cmd);
3512 int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3514 const char *action;
3516 if (commit && *commit) {
3517 action = reflog_message(opts, "start", "checkout %s", commit);
3518 if (run_git_checkout(opts, commit, action))
3519 return error(_("could not checkout %s"), commit);
3522 return 0;
3525 static int checkout_onto(struct replay_opts *opts,
3526 const char *onto_name, const char *onto,
3527 const char *orig_head)
3529 struct object_id oid;
3530 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3532 if (get_oid(orig_head, &oid))
3533 return error(_("%s: not a valid OID"), orig_head);
3535 if (run_git_checkout(opts, onto, action)) {
3536 apply_autostash(opts);
3537 sequencer_remove_state(opts);
3538 return error(_("could not detach HEAD"));
3541 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3544 static int stopped_at_head(struct repository *r)
3546 struct object_id head;
3547 struct commit *commit;
3548 struct commit_message message;
3550 if (get_oid("HEAD", &head) ||
3551 !(commit = lookup_commit(r, &head)) ||
3552 parse_commit(commit) || get_message(commit, &message))
3553 fprintf(stderr, _("Stopped at HEAD\n"));
3554 else {
3555 fprintf(stderr, _("Stopped at %s\n"), message.label);
3556 free_message(commit, &message);
3558 return 0;
3562 static const char rescheduled_advice[] =
3563 N_("Could not execute the todo command\n"
3564 "\n"
3565 " %.*s"
3566 "\n"
3567 "It has been rescheduled; To edit the command before continuing, please\n"
3568 "edit the todo list first:\n"
3569 "\n"
3570 " git rebase --edit-todo\n"
3571 " git rebase --continue\n");
3573 static int pick_commits(struct repository *r,
3574 struct todo_list *todo_list,
3575 struct replay_opts *opts)
3577 int res = 0, reschedule = 0;
3579 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3580 if (opts->allow_ff)
3581 assert(!(opts->signoff || opts->no_commit ||
3582 opts->record_origin || opts->edit));
3583 if (read_and_refresh_cache(r, opts))
3584 return -1;
3586 while (todo_list->current < todo_list->nr) {
3587 struct todo_item *item = todo_list->items + todo_list->current;
3588 if (save_todo(todo_list, opts))
3589 return -1;
3590 if (is_rebase_i(opts)) {
3591 if (item->command != TODO_COMMENT) {
3592 FILE *f = fopen(rebase_path_msgnum(), "w");
3594 todo_list->done_nr++;
3596 if (f) {
3597 fprintf(f, "%d\n", todo_list->done_nr);
3598 fclose(f);
3600 if (!opts->quiet)
3601 fprintf(stderr, "Rebasing (%d/%d)%s",
3602 todo_list->done_nr,
3603 todo_list->total_nr,
3604 opts->verbose ? "\n" : "\r");
3606 unlink(rebase_path_message());
3607 unlink(rebase_path_author_script());
3608 unlink(rebase_path_stopped_sha());
3609 unlink(rebase_path_amend());
3610 unlink(git_path_merge_head(the_repository));
3611 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3613 if (item->command == TODO_BREAK)
3614 return stopped_at_head(r);
3616 if (item->command <= TODO_SQUASH) {
3617 if (is_rebase_i(opts))
3618 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3619 command_to_string(item->command), NULL),
3621 res = do_pick_commit(r, item->command, item->commit,
3622 opts, is_final_fixup(todo_list));
3623 if (is_rebase_i(opts) && res < 0) {
3624 /* Reschedule */
3625 advise(_(rescheduled_advice),
3626 get_item_line_length(todo_list,
3627 todo_list->current),
3628 get_item_line(todo_list,
3629 todo_list->current));
3630 todo_list->current--;
3631 if (save_todo(todo_list, opts))
3632 return -1;
3634 if (item->command == TODO_EDIT) {
3635 struct commit *commit = item->commit;
3636 if (!res)
3637 fprintf(stderr,
3638 _("Stopped at %s... %.*s\n"),
3639 short_commit_name(commit),
3640 item->arg_len, item->arg);
3641 return error_with_patch(r, commit,
3642 item->arg, item->arg_len, opts, res,
3643 !res);
3645 if (is_rebase_i(opts) && !res)
3646 record_in_rewritten(&item->commit->object.oid,
3647 peek_command(todo_list, 1));
3648 if (res && is_fixup(item->command)) {
3649 if (res == 1)
3650 intend_to_amend();
3651 return error_failed_squash(r, item->commit, opts,
3652 item->arg_len, item->arg);
3653 } else if (res && is_rebase_i(opts) && item->commit) {
3654 int to_amend = 0;
3655 struct object_id oid;
3658 * If we are rewording and have either
3659 * fast-forwarded already, or are about to
3660 * create a new root commit, we want to amend,
3661 * otherwise we do not.
3663 if (item->command == TODO_REWORD &&
3664 !get_oid("HEAD", &oid) &&
3665 (oideq(&item->commit->object.oid, &oid) ||
3666 (opts->have_squash_onto &&
3667 oideq(&opts->squash_onto, &oid))))
3668 to_amend = 1;
3670 return res | error_with_patch(r, item->commit,
3671 item->arg, item->arg_len, opts,
3672 res, to_amend);
3674 } else if (item->command == TODO_EXEC) {
3675 char *end_of_arg = (char *)(item->arg + item->arg_len);
3676 int saved = *end_of_arg;
3677 struct stat st;
3679 *end_of_arg = '\0';
3680 res = do_exec(r, item->arg);
3681 *end_of_arg = saved;
3683 if (res) {
3684 if (opts->reschedule_failed_exec)
3685 reschedule = 1;
3686 } else if (stat(get_todo_path(opts), &st))
3687 res = error_errno(_("could not stat '%s'"),
3688 get_todo_path(opts));
3689 else if (match_stat_data(&todo_list->stat, &st)) {
3690 /* Reread the todo file if it has changed. */
3691 todo_list_release(todo_list);
3692 if (read_populate_todo(r, todo_list, opts))
3693 res = -1; /* message was printed */
3694 /* `current` will be incremented below */
3695 todo_list->current = -1;
3697 } else if (item->command == TODO_LABEL) {
3698 if ((res = do_label(r, item->arg, item->arg_len)))
3699 reschedule = 1;
3700 } else if (item->command == TODO_RESET) {
3701 if ((res = do_reset(r, item->arg, item->arg_len, opts)))
3702 reschedule = 1;
3703 } else if (item->command == TODO_MERGE) {
3704 if ((res = do_merge(r, item->commit,
3705 item->arg, item->arg_len,
3706 item->flags, opts)) < 0)
3707 reschedule = 1;
3708 else if (item->commit)
3709 record_in_rewritten(&item->commit->object.oid,
3710 peek_command(todo_list, 1));
3711 if (res > 0)
3712 /* failed with merge conflicts */
3713 return error_with_patch(r, item->commit,
3714 item->arg,
3715 item->arg_len, opts,
3716 res, 0);
3717 } else if (!is_noop(item->command))
3718 return error(_("unknown command %d"), item->command);
3720 if (reschedule) {
3721 advise(_(rescheduled_advice),
3722 get_item_line_length(todo_list,
3723 todo_list->current),
3724 get_item_line(todo_list, todo_list->current));
3725 todo_list->current--;
3726 if (save_todo(todo_list, opts))
3727 return -1;
3728 if (item->commit)
3729 return error_with_patch(r,
3730 item->commit,
3731 item->arg,
3732 item->arg_len, opts,
3733 res, 0);
3736 todo_list->current++;
3737 if (res)
3738 return res;
3741 if (is_rebase_i(opts)) {
3742 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3743 struct stat st;
3745 /* Stopped in the middle, as planned? */
3746 if (todo_list->current < todo_list->nr)
3747 return 0;
3749 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3750 starts_with(head_ref.buf, "refs/")) {
3751 const char *msg;
3752 struct object_id head, orig;
3753 int res;
3755 if (get_oid("HEAD", &head)) {
3756 res = error(_("cannot read HEAD"));
3757 cleanup_head_ref:
3758 strbuf_release(&head_ref);
3759 strbuf_release(&buf);
3760 return res;
3762 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3763 get_oid_hex(buf.buf, &orig)) {
3764 res = error(_("could not read orig-head"));
3765 goto cleanup_head_ref;
3767 strbuf_reset(&buf);
3768 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3769 res = error(_("could not read 'onto'"));
3770 goto cleanup_head_ref;
3772 msg = reflog_message(opts, "finish", "%s onto %s",
3773 head_ref.buf, buf.buf);
3774 if (update_ref(msg, head_ref.buf, &head, &orig,
3775 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3776 res = error(_("could not update %s"),
3777 head_ref.buf);
3778 goto cleanup_head_ref;
3780 msg = reflog_message(opts, "finish", "returning to %s",
3781 head_ref.buf);
3782 if (create_symref("HEAD", head_ref.buf, msg)) {
3783 res = error(_("could not update HEAD to %s"),
3784 head_ref.buf);
3785 goto cleanup_head_ref;
3787 strbuf_reset(&buf);
3790 if (opts->verbose) {
3791 struct rev_info log_tree_opt;
3792 struct object_id orig, head;
3794 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3795 repo_init_revisions(r, &log_tree_opt, NULL);
3796 log_tree_opt.diff = 1;
3797 log_tree_opt.diffopt.output_format =
3798 DIFF_FORMAT_DIFFSTAT;
3799 log_tree_opt.disable_stdin = 1;
3801 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3802 !get_oid(buf.buf, &orig) &&
3803 !get_oid("HEAD", &head)) {
3804 diff_tree_oid(&orig, &head, "",
3805 &log_tree_opt.diffopt);
3806 log_tree_diff_flush(&log_tree_opt);
3809 flush_rewritten_pending();
3810 if (!stat(rebase_path_rewritten_list(), &st) &&
3811 st.st_size > 0) {
3812 struct child_process child = CHILD_PROCESS_INIT;
3813 const char *post_rewrite_hook =
3814 find_hook("post-rewrite");
3816 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3817 child.git_cmd = 1;
3818 argv_array_push(&child.args, "notes");
3819 argv_array_push(&child.args, "copy");
3820 argv_array_push(&child.args, "--for-rewrite=rebase");
3821 /* we don't care if this copying failed */
3822 run_command(&child);
3824 if (post_rewrite_hook) {
3825 struct child_process hook = CHILD_PROCESS_INIT;
3827 hook.in = open(rebase_path_rewritten_list(),
3828 O_RDONLY);
3829 hook.stdout_to_stderr = 1;
3830 hook.trace2_hook_name = "post-rewrite";
3831 argv_array_push(&hook.args, post_rewrite_hook);
3832 argv_array_push(&hook.args, "rebase");
3833 /* we don't care if this hook failed */
3834 run_command(&hook);
3837 apply_autostash(opts);
3839 if (!opts->quiet)
3840 fprintf(stderr,
3841 "Successfully rebased and updated %s.\n",
3842 head_ref.buf);
3844 strbuf_release(&buf);
3845 strbuf_release(&head_ref);
3849 * Sequence of picks finished successfully; cleanup by
3850 * removing the .git/sequencer directory
3852 return sequencer_remove_state(opts);
3855 static int continue_single_pick(struct repository *r)
3857 const char *argv[] = { "commit", NULL };
3859 if (!file_exists(git_path_cherry_pick_head(r)) &&
3860 !file_exists(git_path_revert_head(r)))
3861 return error(_("no cherry-pick or revert in progress"));
3862 return run_command_v_opt(argv, RUN_GIT_CMD);
3865 static int commit_staged_changes(struct repository *r,
3866 struct replay_opts *opts,
3867 struct todo_list *todo_list)
3869 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3870 unsigned int final_fixup = 0, is_clean;
3872 if (has_unstaged_changes(r, 1))
3873 return error(_("cannot rebase: You have unstaged changes."));
3875 is_clean = !has_uncommitted_changes(r, 0);
3877 if (file_exists(rebase_path_amend())) {
3878 struct strbuf rev = STRBUF_INIT;
3879 struct object_id head, to_amend;
3881 if (get_oid("HEAD", &head))
3882 return error(_("cannot amend non-existing commit"));
3883 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3884 return error(_("invalid file: '%s'"), rebase_path_amend());
3885 if (get_oid_hex(rev.buf, &to_amend))
3886 return error(_("invalid contents: '%s'"),
3887 rebase_path_amend());
3888 if (!is_clean && !oideq(&head, &to_amend))
3889 return error(_("\nYou have uncommitted changes in your "
3890 "working tree. Please, commit them\n"
3891 "first and then run 'git rebase "
3892 "--continue' again."));
3894 * When skipping a failed fixup/squash, we need to edit the
3895 * commit message, the current fixup list and count, and if it
3896 * was the last fixup/squash in the chain, we need to clean up
3897 * the commit message and if there was a squash, let the user
3898 * edit it.
3900 if (!is_clean || !opts->current_fixup_count)
3901 ; /* this is not the final fixup */
3902 else if (!oideq(&head, &to_amend) ||
3903 !file_exists(rebase_path_stopped_sha())) {
3904 /* was a final fixup or squash done manually? */
3905 if (!is_fixup(peek_command(todo_list, 0))) {
3906 unlink(rebase_path_fixup_msg());
3907 unlink(rebase_path_squash_msg());
3908 unlink(rebase_path_current_fixups());
3909 strbuf_reset(&opts->current_fixups);
3910 opts->current_fixup_count = 0;
3912 } else {
3913 /* we are in a fixup/squash chain */
3914 const char *p = opts->current_fixups.buf;
3915 int len = opts->current_fixups.len;
3917 opts->current_fixup_count--;
3918 if (!len)
3919 BUG("Incorrect current_fixups:\n%s", p);
3920 while (len && p[len - 1] != '\n')
3921 len--;
3922 strbuf_setlen(&opts->current_fixups, len);
3923 if (write_message(p, len, rebase_path_current_fixups(),
3924 0) < 0)
3925 return error(_("could not write file: '%s'"),
3926 rebase_path_current_fixups());
3929 * If a fixup/squash in a fixup/squash chain failed, the
3930 * commit message is already correct, no need to commit
3931 * it again.
3933 * Only if it is the final command in the fixup/squash
3934 * chain, and only if the chain is longer than a single
3935 * fixup/squash command (which was just skipped), do we
3936 * actually need to re-commit with a cleaned up commit
3937 * message.
3939 if (opts->current_fixup_count > 0 &&
3940 !is_fixup(peek_command(todo_list, 0))) {
3941 final_fixup = 1;
3943 * If there was not a single "squash" in the
3944 * chain, we only need to clean up the commit
3945 * message, no need to bother the user with
3946 * opening the commit message in the editor.
3948 if (!starts_with(p, "squash ") &&
3949 !strstr(p, "\nsquash "))
3950 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3951 } else if (is_fixup(peek_command(todo_list, 0))) {
3953 * We need to update the squash message to skip
3954 * the latest commit message.
3956 struct commit *commit;
3957 const char *path = rebase_path_squash_msg();
3959 if (parse_head(r, &commit) ||
3960 !(p = get_commit_buffer(commit, NULL)) ||
3961 write_message(p, strlen(p), path, 0)) {
3962 unuse_commit_buffer(commit, p);
3963 return error(_("could not write file: "
3964 "'%s'"), path);
3966 unuse_commit_buffer(commit, p);
3970 strbuf_release(&rev);
3971 flags |= AMEND_MSG;
3974 if (is_clean) {
3975 const char *cherry_pick_head = git_path_cherry_pick_head(r);
3977 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3978 return error(_("could not remove CHERRY_PICK_HEAD"));
3979 if (!final_fixup)
3980 return 0;
3983 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
3984 opts, flags))
3985 return error(_("could not commit staged changes."));
3986 unlink(rebase_path_amend());
3987 unlink(git_path_merge_head(the_repository));
3988 if (final_fixup) {
3989 unlink(rebase_path_fixup_msg());
3990 unlink(rebase_path_squash_msg());
3992 if (opts->current_fixup_count > 0) {
3994 * Whether final fixup or not, we just cleaned up the commit
3995 * message...
3997 unlink(rebase_path_current_fixups());
3998 strbuf_reset(&opts->current_fixups);
3999 opts->current_fixup_count = 0;
4001 return 0;
4004 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4006 struct todo_list todo_list = TODO_LIST_INIT;
4007 int res;
4009 if (read_and_refresh_cache(r, opts))
4010 return -1;
4012 if (read_populate_opts(opts))
4013 return -1;
4014 if (is_rebase_i(opts)) {
4015 if ((res = read_populate_todo(r, &todo_list, opts)))
4016 goto release_todo_list;
4017 if (commit_staged_changes(r, opts, &todo_list))
4018 return -1;
4019 } else if (!file_exists(get_todo_path(opts)))
4020 return continue_single_pick(r);
4021 else if ((res = read_populate_todo(r, &todo_list, opts)))
4022 goto release_todo_list;
4024 if (!is_rebase_i(opts)) {
4025 /* Verify that the conflict has been resolved */
4026 if (file_exists(git_path_cherry_pick_head(r)) ||
4027 file_exists(git_path_revert_head(r))) {
4028 res = continue_single_pick(r);
4029 if (res)
4030 goto release_todo_list;
4032 if (index_differs_from(r, "HEAD", NULL, 0)) {
4033 res = error_dirty_index(r, opts);
4034 goto release_todo_list;
4036 todo_list.current++;
4037 } else if (file_exists(rebase_path_stopped_sha())) {
4038 struct strbuf buf = STRBUF_INIT;
4039 struct object_id oid;
4041 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4042 !get_oid_committish(buf.buf, &oid))
4043 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4044 strbuf_release(&buf);
4047 res = pick_commits(r, &todo_list, opts);
4048 release_todo_list:
4049 todo_list_release(&todo_list);
4050 return res;
4053 static int single_pick(struct repository *r,
4054 struct commit *cmit,
4055 struct replay_opts *opts)
4057 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4058 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4059 TODO_PICK : TODO_REVERT, cmit, opts, 0);
4062 int sequencer_pick_revisions(struct repository *r,
4063 struct replay_opts *opts)
4065 struct todo_list todo_list = TODO_LIST_INIT;
4066 struct object_id oid;
4067 int i, res;
4069 assert(opts->revs);
4070 if (read_and_refresh_cache(r, opts))
4071 return -1;
4073 for (i = 0; i < opts->revs->pending.nr; i++) {
4074 struct object_id oid;
4075 const char *name = opts->revs->pending.objects[i].name;
4077 /* This happens when using --stdin. */
4078 if (!strlen(name))
4079 continue;
4081 if (!get_oid(name, &oid)) {
4082 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4083 enum object_type type = oid_object_info(r,
4084 &oid,
4085 NULL);
4086 return error(_("%s: can't cherry-pick a %s"),
4087 name, type_name(type));
4089 } else
4090 return error(_("%s: bad revision"), name);
4094 * If we were called as "git cherry-pick <commit>", just
4095 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4096 * REVERT_HEAD, and don't touch the sequencer state.
4097 * This means it is possible to cherry-pick in the middle
4098 * of a cherry-pick sequence.
4100 if (opts->revs->cmdline.nr == 1 &&
4101 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4102 opts->revs->no_walk &&
4103 !opts->revs->cmdline.rev->flags) {
4104 struct commit *cmit;
4105 if (prepare_revision_walk(opts->revs))
4106 return error(_("revision walk setup failed"));
4107 cmit = get_revision(opts->revs);
4108 if (!cmit)
4109 return error(_("empty commit set passed"));
4110 if (get_revision(opts->revs))
4111 BUG("unexpected extra commit from walk");
4112 return single_pick(r, cmit, opts);
4116 * Start a new cherry-pick/ revert sequence; but
4117 * first, make sure that an existing one isn't in
4118 * progress
4121 if (walk_revs_populate_todo(&todo_list, opts) ||
4122 create_seq_dir() < 0)
4123 return -1;
4124 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4125 return error(_("can't revert as initial commit"));
4126 if (save_head(oid_to_hex(&oid)))
4127 return -1;
4128 if (save_opts(opts))
4129 return -1;
4130 update_abort_safety_file();
4131 res = pick_commits(r, &todo_list, opts);
4132 todo_list_release(&todo_list);
4133 return res;
4136 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4138 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4139 struct strbuf sob = STRBUF_INIT;
4140 int has_footer;
4142 strbuf_addstr(&sob, sign_off_header);
4143 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4144 strbuf_addch(&sob, '\n');
4146 if (!ignore_footer)
4147 strbuf_complete_line(msgbuf);
4150 * If the whole message buffer is equal to the sob, pretend that we
4151 * found a conforming footer with a matching sob
4153 if (msgbuf->len - ignore_footer == sob.len &&
4154 !strncmp(msgbuf->buf, sob.buf, sob.len))
4155 has_footer = 3;
4156 else
4157 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4159 if (!has_footer) {
4160 const char *append_newlines = NULL;
4161 size_t len = msgbuf->len - ignore_footer;
4163 if (!len) {
4165 * The buffer is completely empty. Leave foom for
4166 * the title and body to be filled in by the user.
4168 append_newlines = "\n\n";
4169 } else if (len == 1) {
4171 * Buffer contains a single newline. Add another
4172 * so that we leave room for the title and body.
4174 append_newlines = "\n";
4175 } else if (msgbuf->buf[len - 2] != '\n') {
4177 * Buffer ends with a single newline. Add another
4178 * so that there is an empty line between the message
4179 * body and the sob.
4181 append_newlines = "\n";
4182 } /* else, the buffer already ends with two newlines. */
4184 if (append_newlines)
4185 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4186 append_newlines, strlen(append_newlines));
4189 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4190 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4191 sob.buf, sob.len);
4193 strbuf_release(&sob);
4196 struct labels_entry {
4197 struct hashmap_entry entry;
4198 char label[FLEX_ARRAY];
4201 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4202 const struct labels_entry *b, const void *key)
4204 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4207 struct string_entry {
4208 struct oidmap_entry entry;
4209 char string[FLEX_ARRAY];
4212 struct label_state {
4213 struct oidmap commit2label;
4214 struct hashmap labels;
4215 struct strbuf buf;
4218 static const char *label_oid(struct object_id *oid, const char *label,
4219 struct label_state *state)
4221 struct labels_entry *labels_entry;
4222 struct string_entry *string_entry;
4223 struct object_id dummy;
4224 size_t len;
4225 int i;
4227 string_entry = oidmap_get(&state->commit2label, oid);
4228 if (string_entry)
4229 return string_entry->string;
4232 * For "uninteresting" commits, i.e. commits that are not to be
4233 * rebased, and which can therefore not be labeled, we use a unique
4234 * abbreviation of the commit name. This is slightly more complicated
4235 * than calling find_unique_abbrev() because we also need to make
4236 * sure that the abbreviation does not conflict with any other
4237 * label.
4239 * We disallow "interesting" commits to be labeled by a string that
4240 * is a valid full-length hash, to ensure that we always can find an
4241 * abbreviation for any uninteresting commit's names that does not
4242 * clash with any other label.
4244 if (!label) {
4245 char *p;
4247 strbuf_reset(&state->buf);
4248 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4249 label = p = state->buf.buf;
4251 find_unique_abbrev_r(p, oid, default_abbrev);
4254 * We may need to extend the abbreviated hash so that there is
4255 * no conflicting label.
4257 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4258 size_t i = strlen(p) + 1;
4260 oid_to_hex_r(p, oid);
4261 for (; i < GIT_SHA1_HEXSZ; i++) {
4262 char save = p[i];
4263 p[i] = '\0';
4264 if (!hashmap_get_from_hash(&state->labels,
4265 strihash(p), p))
4266 break;
4267 p[i] = save;
4270 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4271 !get_oid_hex(label, &dummy)) ||
4272 (len == 1 && *label == '#') ||
4273 hashmap_get_from_hash(&state->labels,
4274 strihash(label), label)) {
4276 * If the label already exists, or if the label is a valid full
4277 * OID, or the label is a '#' (which we use as a separator
4278 * between merge heads and oneline), we append a dash and a
4279 * number to make it unique.
4281 struct strbuf *buf = &state->buf;
4283 strbuf_reset(buf);
4284 strbuf_add(buf, label, len);
4286 for (i = 2; ; i++) {
4287 strbuf_setlen(buf, len);
4288 strbuf_addf(buf, "-%d", i);
4289 if (!hashmap_get_from_hash(&state->labels,
4290 strihash(buf->buf),
4291 buf->buf))
4292 break;
4295 label = buf->buf;
4298 FLEX_ALLOC_STR(labels_entry, label, label);
4299 hashmap_entry_init(labels_entry, strihash(label));
4300 hashmap_add(&state->labels, labels_entry);
4302 FLEX_ALLOC_STR(string_entry, string, label);
4303 oidcpy(&string_entry->entry.oid, oid);
4304 oidmap_put(&state->commit2label, string_entry);
4306 return string_entry->string;
4309 static int make_script_with_merges(struct pretty_print_context *pp,
4310 struct rev_info *revs, FILE *out,
4311 unsigned flags)
4313 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4314 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4315 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4316 struct strbuf label = STRBUF_INIT;
4317 struct commit_list *commits = NULL, **tail = &commits, *iter;
4318 struct commit_list *tips = NULL, **tips_tail = &tips;
4319 struct commit *commit;
4320 struct oidmap commit2todo = OIDMAP_INIT;
4321 struct string_entry *entry;
4322 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4323 shown = OIDSET_INIT;
4324 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4326 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4327 const char *cmd_pick = abbr ? "p" : "pick",
4328 *cmd_label = abbr ? "l" : "label",
4329 *cmd_reset = abbr ? "t" : "reset",
4330 *cmd_merge = abbr ? "m" : "merge";
4332 oidmap_init(&commit2todo, 0);
4333 oidmap_init(&state.commit2label, 0);
4334 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4335 strbuf_init(&state.buf, 32);
4337 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4338 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4339 FLEX_ALLOC_STR(entry, string, "onto");
4340 oidcpy(&entry->entry.oid, oid);
4341 oidmap_put(&state.commit2label, entry);
4345 * First phase:
4346 * - get onelines for all commits
4347 * - gather all branch tips (i.e. 2nd or later parents of merges)
4348 * - label all branch tips
4350 while ((commit = get_revision(revs))) {
4351 struct commit_list *to_merge;
4352 const char *p1, *p2;
4353 struct object_id *oid;
4354 int is_empty;
4356 tail = &commit_list_insert(commit, tail)->next;
4357 oidset_insert(&interesting, &commit->object.oid);
4359 is_empty = is_original_commit_empty(commit);
4360 if (!is_empty && (commit->object.flags & PATCHSAME))
4361 continue;
4363 strbuf_reset(&oneline);
4364 pretty_print_commit(pp, commit, &oneline);
4366 to_merge = commit->parents ? commit->parents->next : NULL;
4367 if (!to_merge) {
4368 /* non-merge commit: easy case */
4369 strbuf_reset(&buf);
4370 if (!keep_empty && is_empty)
4371 strbuf_addf(&buf, "%c ", comment_line_char);
4372 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4373 oid_to_hex(&commit->object.oid),
4374 oneline.buf);
4376 FLEX_ALLOC_STR(entry, string, buf.buf);
4377 oidcpy(&entry->entry.oid, &commit->object.oid);
4378 oidmap_put(&commit2todo, entry);
4380 continue;
4383 /* Create a label */
4384 strbuf_reset(&label);
4385 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4386 (p1 = strchr(p1, '\'')) &&
4387 (p2 = strchr(++p1, '\'')))
4388 strbuf_add(&label, p1, p2 - p1);
4389 else if (skip_prefix(oneline.buf, "Merge pull request ",
4390 &p1) &&
4391 (p1 = strstr(p1, " from ")))
4392 strbuf_addstr(&label, p1 + strlen(" from "));
4393 else
4394 strbuf_addbuf(&label, &oneline);
4396 for (p1 = label.buf; *p1; p1++)
4397 if (isspace(*p1))
4398 *(char *)p1 = '-';
4400 strbuf_reset(&buf);
4401 strbuf_addf(&buf, "%s -C %s",
4402 cmd_merge, oid_to_hex(&commit->object.oid));
4404 /* label the tips of merged branches */
4405 for (; to_merge; to_merge = to_merge->next) {
4406 oid = &to_merge->item->object.oid;
4407 strbuf_addch(&buf, ' ');
4409 if (!oidset_contains(&interesting, oid)) {
4410 strbuf_addstr(&buf, label_oid(oid, NULL,
4411 &state));
4412 continue;
4415 tips_tail = &commit_list_insert(to_merge->item,
4416 tips_tail)->next;
4418 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4420 strbuf_addf(&buf, " # %s", oneline.buf);
4422 FLEX_ALLOC_STR(entry, string, buf.buf);
4423 oidcpy(&entry->entry.oid, &commit->object.oid);
4424 oidmap_put(&commit2todo, entry);
4428 * Second phase:
4429 * - label branch points
4430 * - add HEAD to the branch tips
4432 for (iter = commits; iter; iter = iter->next) {
4433 struct commit_list *parent = iter->item->parents;
4434 for (; parent; parent = parent->next) {
4435 struct object_id *oid = &parent->item->object.oid;
4436 if (!oidset_contains(&interesting, oid))
4437 continue;
4438 if (oidset_insert(&child_seen, oid))
4439 label_oid(oid, "branch-point", &state);
4442 /* Add HEAD as implict "tip of branch" */
4443 if (!iter->next)
4444 tips_tail = &commit_list_insert(iter->item,
4445 tips_tail)->next;
4449 * Third phase: output the todo list. This is a bit tricky, as we
4450 * want to avoid jumping back and forth between revisions. To
4451 * accomplish that goal, we walk backwards from the branch tips,
4452 * gathering commits not yet shown, reversing the list on the fly,
4453 * then outputting that list (labeling revisions as needed).
4455 fprintf(out, "%s onto\n", cmd_label);
4456 for (iter = tips; iter; iter = iter->next) {
4457 struct commit_list *list = NULL, *iter2;
4459 commit = iter->item;
4460 if (oidset_contains(&shown, &commit->object.oid))
4461 continue;
4462 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4464 if (entry)
4465 fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4466 else
4467 fprintf(out, "\n");
4469 while (oidset_contains(&interesting, &commit->object.oid) &&
4470 !oidset_contains(&shown, &commit->object.oid)) {
4471 commit_list_insert(commit, &list);
4472 if (!commit->parents) {
4473 commit = NULL;
4474 break;
4476 commit = commit->parents->item;
4479 if (!commit)
4480 fprintf(out, "%s %s\n", cmd_reset,
4481 rebase_cousins ? "onto" : "[new root]");
4482 else {
4483 const char *to = NULL;
4485 entry = oidmap_get(&state.commit2label,
4486 &commit->object.oid);
4487 if (entry)
4488 to = entry->string;
4489 else if (!rebase_cousins)
4490 to = label_oid(&commit->object.oid, NULL,
4491 &state);
4493 if (!to || !strcmp(to, "onto"))
4494 fprintf(out, "%s onto\n", cmd_reset);
4495 else {
4496 strbuf_reset(&oneline);
4497 pretty_print_commit(pp, commit, &oneline);
4498 fprintf(out, "%s %s # %s\n",
4499 cmd_reset, to, oneline.buf);
4503 for (iter2 = list; iter2; iter2 = iter2->next) {
4504 struct object_id *oid = &iter2->item->object.oid;
4505 entry = oidmap_get(&commit2todo, oid);
4506 /* only show if not already upstream */
4507 if (entry)
4508 fprintf(out, "%s\n", entry->string);
4509 entry = oidmap_get(&state.commit2label, oid);
4510 if (entry)
4511 fprintf(out, "%s %s\n",
4512 cmd_label, entry->string);
4513 oidset_insert(&shown, oid);
4516 free_commit_list(list);
4519 free_commit_list(commits);
4520 free_commit_list(tips);
4522 strbuf_release(&label);
4523 strbuf_release(&oneline);
4524 strbuf_release(&buf);
4526 oidmap_free(&commit2todo, 1);
4527 oidmap_free(&state.commit2label, 1);
4528 hashmap_free(&state.labels, 1);
4529 strbuf_release(&state.buf);
4531 return 0;
4534 int sequencer_make_script(struct repository *r, FILE *out,
4535 int argc, const char **argv,
4536 unsigned flags)
4538 char *format = NULL;
4539 struct pretty_print_context pp = {0};
4540 struct strbuf buf = STRBUF_INIT;
4541 struct rev_info revs;
4542 struct commit *commit;
4543 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4544 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4545 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4547 repo_init_revisions(r, &revs, NULL);
4548 revs.verbose_header = 1;
4549 if (!rebase_merges)
4550 revs.max_parents = 1;
4551 revs.cherry_mark = 1;
4552 revs.limited = 1;
4553 revs.reverse = 1;
4554 revs.right_only = 1;
4555 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4556 revs.topo_order = 1;
4558 revs.pretty_given = 1;
4559 git_config_get_string("rebase.instructionFormat", &format);
4560 if (!format || !*format) {
4561 free(format);
4562 format = xstrdup("%s");
4564 get_commit_format(format, &revs);
4565 free(format);
4566 pp.fmt = revs.commit_format;
4567 pp.output_encoding = get_log_output_encoding();
4569 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4570 return error(_("make_script: unhandled options"));
4572 if (prepare_revision_walk(&revs) < 0)
4573 return error(_("make_script: error preparing revisions"));
4575 if (rebase_merges)
4576 return make_script_with_merges(&pp, &revs, out, flags);
4578 while ((commit = get_revision(&revs))) {
4579 int is_empty = is_original_commit_empty(commit);
4581 if (!is_empty && (commit->object.flags & PATCHSAME))
4582 continue;
4583 strbuf_reset(&buf);
4584 if (!keep_empty && is_empty)
4585 strbuf_addf(&buf, "%c ", comment_line_char);
4586 strbuf_addf(&buf, "%s %s ", insn,
4587 oid_to_hex(&commit->object.oid));
4588 pretty_print_commit(&pp, commit, &buf);
4589 strbuf_addch(&buf, '\n');
4590 fputs(buf.buf, out);
4592 strbuf_release(&buf);
4593 return 0;
4597 * Add commands after pick and (series of) squash/fixup commands
4598 * in the todo list.
4600 int sequencer_add_exec_commands(struct repository *r,
4601 const char *commands)
4603 const char *todo_file = rebase_path_todo();
4604 struct todo_list todo_list = TODO_LIST_INIT;
4605 struct strbuf *buf = &todo_list.buf;
4606 size_t offset = 0, commands_len = strlen(commands);
4607 int i, insert;
4609 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4610 return error(_("could not read '%s'."), todo_file);
4612 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
4613 todo_list_release(&todo_list);
4614 return error(_("unusable todo list: '%s'"), todo_file);
4618 * Insert <commands> after every pick. Here, fixup/squash chains
4619 * are considered part of the pick, so we insert the commands *after*
4620 * those chains if there are any.
4622 insert = -1;
4623 for (i = 0; i < todo_list.nr; i++) {
4624 enum todo_command command = todo_list.items[i].command;
4626 if (insert >= 0) {
4627 /* skip fixup/squash chains */
4628 if (command == TODO_COMMENT)
4629 continue;
4630 else if (is_fixup(command)) {
4631 insert = i + 1;
4632 continue;
4634 strbuf_insert(buf,
4635 todo_list.items[insert].offset_in_buf +
4636 offset, commands, commands_len);
4637 offset += commands_len;
4638 insert = -1;
4641 if (command == TODO_PICK || command == TODO_MERGE)
4642 insert = i + 1;
4645 /* insert or append final <commands> */
4646 if (insert >= 0 && insert < todo_list.nr)
4647 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4648 offset, commands, commands_len);
4649 else if (insert >= 0 || !offset)
4650 strbuf_add(buf, commands, commands_len);
4652 i = write_message(buf->buf, buf->len, todo_file, 0);
4653 todo_list_release(&todo_list);
4654 return i;
4657 int transform_todos(struct repository *r, unsigned flags)
4659 const char *todo_file = rebase_path_todo();
4660 struct todo_list todo_list = TODO_LIST_INIT;
4661 struct strbuf buf = STRBUF_INIT;
4662 struct todo_item *item;
4663 int i;
4665 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4666 return error(_("could not read '%s'."), todo_file);
4668 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
4669 todo_list_release(&todo_list);
4670 return error(_("unusable todo list: '%s'"), todo_file);
4673 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4674 /* if the item is not a command write it and continue */
4675 if (item->command >= TODO_COMMENT) {
4676 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4677 continue;
4680 /* add command to the buffer */
4681 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4682 strbuf_addch(&buf, command_to_char(item->command));
4683 else
4684 strbuf_addstr(&buf, command_to_string(item->command));
4686 /* add commit id */
4687 if (item->commit) {
4688 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4689 short_commit_name(item->commit) :
4690 oid_to_hex(&item->commit->object.oid);
4692 if (item->command == TODO_MERGE) {
4693 if (item->flags & TODO_EDIT_MERGE_MSG)
4694 strbuf_addstr(&buf, " -c");
4695 else
4696 strbuf_addstr(&buf, " -C");
4699 strbuf_addf(&buf, " %s", oid);
4702 /* add all the rest */
4703 if (!item->arg_len)
4704 strbuf_addch(&buf, '\n');
4705 else
4706 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4709 i = write_message(buf.buf, buf.len, todo_file, 0);
4710 todo_list_release(&todo_list);
4711 return i;
4714 enum missing_commit_check_level get_missing_commit_check_level(void)
4716 const char *value;
4718 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4719 !strcasecmp("ignore", value))
4720 return MISSING_COMMIT_CHECK_IGNORE;
4721 if (!strcasecmp("warn", value))
4722 return MISSING_COMMIT_CHECK_WARN;
4723 if (!strcasecmp("error", value))
4724 return MISSING_COMMIT_CHECK_ERROR;
4725 warning(_("unrecognized setting %s for option "
4726 "rebase.missingCommitsCheck. Ignoring."), value);
4727 return MISSING_COMMIT_CHECK_IGNORE;
4730 define_commit_slab(commit_seen, unsigned char);
4732 * Check if the user dropped some commits by mistake
4733 * Behaviour determined by rebase.missingCommitsCheck.
4734 * Check if there is an unrecognized command or a
4735 * bad SHA-1 in a command.
4737 int check_todo_list(struct repository *r)
4739 enum missing_commit_check_level check_level = get_missing_commit_check_level();
4740 struct strbuf todo_file = STRBUF_INIT;
4741 struct todo_list todo_list = TODO_LIST_INIT;
4742 struct strbuf missing = STRBUF_INIT;
4743 int advise_to_edit_todo = 0, res = 0, i;
4744 struct commit_seen commit_seen;
4746 init_commit_seen(&commit_seen);
4748 strbuf_addstr(&todo_file, rebase_path_todo());
4749 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4750 res = -1;
4751 goto leave_check;
4753 advise_to_edit_todo = res =
4754 parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
4756 if (res || check_level == MISSING_COMMIT_CHECK_IGNORE)
4757 goto leave_check;
4759 /* Mark the commits in git-rebase-todo as seen */
4760 for (i = 0; i < todo_list.nr; i++) {
4761 struct commit *commit = todo_list.items[i].commit;
4762 if (commit)
4763 *commit_seen_at(&commit_seen, commit) = 1;
4766 todo_list_release(&todo_list);
4767 strbuf_addstr(&todo_file, ".backup");
4768 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4769 res = -1;
4770 goto leave_check;
4772 strbuf_release(&todo_file);
4773 res = !!parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
4775 /* Find commits in git-rebase-todo.backup yet unseen */
4776 for (i = todo_list.nr - 1; i >= 0; i--) {
4777 struct todo_item *item = todo_list.items + i;
4778 struct commit *commit = item->commit;
4779 if (commit && !*commit_seen_at(&commit_seen, commit)) {
4780 strbuf_addf(&missing, " - %s %.*s\n",
4781 short_commit_name(commit),
4782 item->arg_len, item->arg);
4783 *commit_seen_at(&commit_seen, commit) = 1;
4787 /* Warn about missing commits */
4788 if (!missing.len)
4789 goto leave_check;
4791 if (check_level == MISSING_COMMIT_CHECK_ERROR)
4792 advise_to_edit_todo = res = 1;
4794 fprintf(stderr,
4795 _("Warning: some commits may have been dropped accidentally.\n"
4796 "Dropped commits (newer to older):\n"));
4798 /* Make the list user-friendly and display */
4799 fputs(missing.buf, stderr);
4800 strbuf_release(&missing);
4802 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4803 "explicitly remove a commit.\n\n"
4804 "Use 'git config rebase.missingCommitsCheck' to change "
4805 "the level of warnings.\n"
4806 "The possible behaviours are: ignore, warn, error.\n\n"));
4808 leave_check:
4809 clear_commit_seen(&commit_seen);
4810 strbuf_release(&todo_file);
4811 todo_list_release(&todo_list);
4813 if (advise_to_edit_todo)
4814 fprintf(stderr,
4815 _("You can fix this with 'git rebase --edit-todo' "
4816 "and then run 'git rebase --continue'.\n"
4817 "Or you can abort the rebase with 'git rebase"
4818 " --abort'.\n"));
4820 return res;
4823 static int rewrite_file(const char *path, const char *buf, size_t len)
4825 int rc = 0;
4826 int fd = open(path, O_WRONLY | O_TRUNC);
4827 if (fd < 0)
4828 return error_errno(_("could not open '%s' for writing"), path);
4829 if (write_in_full(fd, buf, len) < 0)
4830 rc = error_errno(_("could not write to '%s'"), path);
4831 if (close(fd) && !rc)
4832 rc = error_errno(_("could not close '%s'"), path);
4833 return rc;
4836 /* skip picking commits whose parents are unchanged */
4837 static int skip_unnecessary_picks(struct repository *r, struct object_id *output_oid)
4839 const char *todo_file = rebase_path_todo();
4840 struct strbuf buf = STRBUF_INIT;
4841 struct todo_list todo_list = TODO_LIST_INIT;
4842 struct object_id *parent_oid;
4843 int fd, i;
4845 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4846 return error(_("could not read 'onto'"));
4847 if (get_oid(buf.buf, output_oid)) {
4848 strbuf_release(&buf);
4849 return error(_("need a HEAD to fixup"));
4851 strbuf_release(&buf);
4853 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4854 return -1;
4855 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
4856 todo_list_release(&todo_list);
4857 return -1;
4860 for (i = 0; i < todo_list.nr; i++) {
4861 struct todo_item *item = todo_list.items + i;
4863 if (item->command >= TODO_NOOP)
4864 continue;
4865 if (item->command != TODO_PICK)
4866 break;
4867 if (parse_commit(item->commit)) {
4868 todo_list_release(&todo_list);
4869 return error(_("could not parse commit '%s'"),
4870 oid_to_hex(&item->commit->object.oid));
4872 if (!item->commit->parents)
4873 break; /* root commit */
4874 if (item->commit->parents->next)
4875 break; /* merge commit */
4876 parent_oid = &item->commit->parents->item->object.oid;
4877 if (!oideq(parent_oid, output_oid))
4878 break;
4879 oidcpy(output_oid, &item->commit->object.oid);
4881 if (i > 0) {
4882 int offset = get_item_line_offset(&todo_list, i);
4883 const char *done_path = rebase_path_done();
4885 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4886 if (fd < 0) {
4887 error_errno(_("could not open '%s' for writing"),
4888 done_path);
4889 todo_list_release(&todo_list);
4890 return -1;
4892 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4893 error_errno(_("could not write to '%s'"), done_path);
4894 todo_list_release(&todo_list);
4895 close(fd);
4896 return -1;
4898 close(fd);
4900 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4901 todo_list.buf.len - offset) < 0) {
4902 todo_list_release(&todo_list);
4903 return -1;
4906 todo_list.current = i;
4907 if (is_fixup(peek_command(&todo_list, 0)))
4908 record_in_rewritten(output_oid, peek_command(&todo_list, 0));
4911 todo_list_release(&todo_list);
4913 return 0;
4916 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
4917 const char *shortrevisions, const char *onto_name,
4918 const char *onto, const char *orig_head, const char *cmd,
4919 unsigned autosquash)
4921 const char *shortonto, *todo_file = rebase_path_todo();
4922 struct todo_list todo_list = TODO_LIST_INIT;
4923 struct strbuf *buf = &(todo_list.buf);
4924 struct object_id oid;
4925 struct stat st;
4927 get_oid(onto, &oid);
4928 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4930 if (!lstat(todo_file, &st) && st.st_size == 0 &&
4931 write_message("noop\n", 5, todo_file, 0))
4932 return -1;
4934 if (autosquash && rearrange_squash(r))
4935 return -1;
4937 if (cmd && *cmd)
4938 sequencer_add_exec_commands(r, cmd);
4940 if (strbuf_read_file(buf, todo_file, 0) < 0)
4941 return error_errno(_("could not read '%s'."), todo_file);
4943 if (parse_insn_buffer(r, buf->buf, &todo_list)) {
4944 todo_list_release(&todo_list);
4945 return error(_("unusable todo list: '%s'"), todo_file);
4948 if (count_commands(&todo_list) == 0) {
4949 apply_autostash(opts);
4950 sequencer_remove_state(opts);
4951 todo_list_release(&todo_list);
4953 return error(_("nothing to do"));
4956 strbuf_addch(buf, '\n');
4957 strbuf_commented_addf(buf, Q_("Rebase %s onto %s (%d command)",
4958 "Rebase %s onto %s (%d commands)",
4959 count_commands(&todo_list)),
4960 shortrevisions, shortonto, count_commands(&todo_list));
4961 append_todo_help(0, flags & TODO_LIST_KEEP_EMPTY, buf);
4963 if (write_message(buf->buf, buf->len, todo_file, 0)) {
4964 todo_list_release(&todo_list);
4965 return -1;
4968 if (copy_file(rebase_path_todo_backup(), todo_file, 0666))
4969 return error(_("could not copy '%s' to '%s'."), todo_file,
4970 rebase_path_todo_backup());
4972 if (transform_todos(r, flags | TODO_LIST_SHORTEN_IDS))
4973 return error(_("could not transform the todo list"));
4975 strbuf_reset(buf);
4977 if (launch_sequence_editor(todo_file, buf, NULL)) {
4978 apply_autostash(opts);
4979 sequencer_remove_state(opts);
4980 todo_list_release(&todo_list);
4982 return -1;
4985 strbuf_stripspace(buf, 1);
4986 if (buf->len == 0) {
4987 apply_autostash(opts);
4988 sequencer_remove_state(opts);
4989 todo_list_release(&todo_list);
4991 return error(_("nothing to do"));
4994 todo_list_release(&todo_list);
4996 if (check_todo_list(r)) {
4997 checkout_onto(opts, onto_name, onto, orig_head);
4998 return -1;
5001 if (transform_todos(r, flags & ~(TODO_LIST_SHORTEN_IDS)))
5002 return error(_("could not transform the todo list"));
5004 if (opts->allow_ff && skip_unnecessary_picks(r, &oid))
5005 return error(_("could not skip unnecessary pick commands"));
5007 if (checkout_onto(opts, onto_name, oid_to_hex(&oid), orig_head))
5008 return -1;
5010 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5011 return -1;
5013 return sequencer_continue(r, opts);
5016 struct subject2item_entry {
5017 struct hashmap_entry entry;
5018 int i;
5019 char subject[FLEX_ARRAY];
5022 static int subject2item_cmp(const void *fndata,
5023 const struct subject2item_entry *a,
5024 const struct subject2item_entry *b, const void *key)
5026 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5029 define_commit_slab(commit_todo_item, struct todo_item *);
5032 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5033 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5034 * after the former, and change "pick" to "fixup"/"squash".
5036 * Note that if the config has specified a custom instruction format, each log
5037 * message will have to be retrieved from the commit (as the oneline in the
5038 * script cannot be trusted) in order to normalize the autosquash arrangement.
5040 int rearrange_squash(struct repository *r)
5042 const char *todo_file = rebase_path_todo();
5043 struct todo_list todo_list = TODO_LIST_INIT;
5044 struct hashmap subject2item;
5045 int res = 0, rearranged = 0, *next, *tail, i;
5046 char **subjects;
5047 struct commit_todo_item commit_todo;
5049 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
5050 return -1;
5051 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
5052 todo_list_release(&todo_list);
5053 return -1;
5056 init_commit_todo_item(&commit_todo);
5058 * The hashmap maps onelines to the respective todo list index.
5060 * If any items need to be rearranged, the next[i] value will indicate
5061 * which item was moved directly after the i'th.
5063 * In that case, last[i] will indicate the index of the latest item to
5064 * be moved to appear after the i'th.
5066 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
5067 NULL, todo_list.nr);
5068 ALLOC_ARRAY(next, todo_list.nr);
5069 ALLOC_ARRAY(tail, todo_list.nr);
5070 ALLOC_ARRAY(subjects, todo_list.nr);
5071 for (i = 0; i < todo_list.nr; i++) {
5072 struct strbuf buf = STRBUF_INIT;
5073 struct todo_item *item = todo_list.items + i;
5074 const char *commit_buffer, *subject, *p;
5075 size_t subject_len;
5076 int i2 = -1;
5077 struct subject2item_entry *entry;
5079 next[i] = tail[i] = -1;
5080 if (!item->commit || item->command == TODO_DROP) {
5081 subjects[i] = NULL;
5082 continue;
5085 if (is_fixup(item->command)) {
5086 todo_list_release(&todo_list);
5087 clear_commit_todo_item(&commit_todo);
5088 return error(_("the script was already rearranged."));
5091 *commit_todo_item_at(&commit_todo, item->commit) = item;
5093 parse_commit(item->commit);
5094 commit_buffer = get_commit_buffer(item->commit, NULL);
5095 find_commit_subject(commit_buffer, &subject);
5096 format_subject(&buf, subject, " ");
5097 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5098 unuse_commit_buffer(item->commit, commit_buffer);
5099 if ((skip_prefix(subject, "fixup! ", &p) ||
5100 skip_prefix(subject, "squash! ", &p))) {
5101 struct commit *commit2;
5103 for (;;) {
5104 while (isspace(*p))
5105 p++;
5106 if (!skip_prefix(p, "fixup! ", &p) &&
5107 !skip_prefix(p, "squash! ", &p))
5108 break;
5111 if ((entry = hashmap_get_from_hash(&subject2item,
5112 strhash(p), p)))
5113 /* found by title */
5114 i2 = entry->i;
5115 else if (!strchr(p, ' ') &&
5116 (commit2 =
5117 lookup_commit_reference_by_name(p)) &&
5118 *commit_todo_item_at(&commit_todo, commit2))
5119 /* found by commit name */
5120 i2 = *commit_todo_item_at(&commit_todo, commit2)
5121 - todo_list.items;
5122 else {
5123 /* copy can be a prefix of the commit subject */
5124 for (i2 = 0; i2 < i; i2++)
5125 if (subjects[i2] &&
5126 starts_with(subjects[i2], p))
5127 break;
5128 if (i2 == i)
5129 i2 = -1;
5132 if (i2 >= 0) {
5133 rearranged = 1;
5134 todo_list.items[i].command =
5135 starts_with(subject, "fixup!") ?
5136 TODO_FIXUP : TODO_SQUASH;
5137 if (next[i2] < 0)
5138 next[i2] = i;
5139 else
5140 next[tail[i2]] = i;
5141 tail[i2] = i;
5142 } else if (!hashmap_get_from_hash(&subject2item,
5143 strhash(subject), subject)) {
5144 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5145 entry->i = i;
5146 hashmap_entry_init(entry, strhash(entry->subject));
5147 hashmap_put(&subject2item, entry);
5151 if (rearranged) {
5152 struct strbuf buf = STRBUF_INIT;
5154 for (i = 0; i < todo_list.nr; i++) {
5155 enum todo_command command = todo_list.items[i].command;
5156 int cur = i;
5159 * Initially, all commands are 'pick's. If it is a
5160 * fixup or a squash now, we have rearranged it.
5162 if (is_fixup(command))
5163 continue;
5165 while (cur >= 0) {
5166 const char *bol =
5167 get_item_line(&todo_list, cur);
5168 const char *eol =
5169 get_item_line(&todo_list, cur + 1);
5171 /* replace 'pick', by 'fixup' or 'squash' */
5172 command = todo_list.items[cur].command;
5173 if (is_fixup(command)) {
5174 strbuf_addstr(&buf,
5175 todo_command_info[command].str);
5176 bol += strcspn(bol, " \t");
5179 strbuf_add(&buf, bol, eol - bol);
5181 cur = next[cur];
5185 res = rewrite_file(todo_file, buf.buf, buf.len);
5186 strbuf_release(&buf);
5189 free(next);
5190 free(tail);
5191 for (i = 0; i < todo_list.nr; i++)
5192 free(subjects[i]);
5193 free(subjects);
5194 hashmap_free(&subject2item, 1);
5195 todo_list_release(&todo_list);
5197 clear_commit_todo_item(&commit_todo);
5198 return res;