fetch: in partial clone, check presence of targets
[git/raj.git] / sequencer.c
blob00cefd129e4a9be73f3003186c90de439ba7d988
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"
35 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
37 const char sign_off_header[] = "Signed-off-by: ";
38 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
40 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
42 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
44 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
45 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
46 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
47 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
49 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
51 * The file containing rebase commands, comments, and empty lines.
52 * This file is created by "git rebase -i" then edited by the user. As
53 * the lines are processed, they are removed from the front of this
54 * file and written to the tail of 'done'.
56 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 * The rebase command lines that have already been processed. A line
59 * is moved here when it is first handled, before any associated user
60 * actions.
62 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
64 * The file to keep track of how many commands were already processed (e.g.
65 * for the prompt).
67 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
69 * The file to keep track of how many commands are to be processed in total
70 * (e.g. for the prompt).
72 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
74 * The commit message that is planned to be used for any changes that
75 * need to be committed following a user interaction.
77 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
79 * The file into which is accumulated the suggested commit message for
80 * squash/fixup commands. When the first of a series of squash/fixups
81 * is seen, the file is created and the commit message from the
82 * previous commit and from the first squash/fixup commit are written
83 * to it. The commit message for each subsequent squash/fixup commit
84 * is appended to the file as it is processed.
86 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
88 * If the current series of squash/fixups has not yet included a squash
89 * command, then this file exists and holds the commit message of the
90 * original "pick" commit. (If the series ends without a "squash"
91 * command, then this can be used as the commit message of the combined
92 * commit without opening the editor.)
94 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
96 * This file contains the list fixup/squash commands that have been
97 * accumulated into message-fixup or message-squash so far.
99 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
101 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
102 * GIT_AUTHOR_DATE that will be used for the commit that is currently
103 * being rebased.
105 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
107 * When an "edit" rebase command is being processed, the SHA1 of the
108 * commit to be edited is recorded in this file. When "git rebase
109 * --continue" is executed, if there are any staged changes then they
110 * will be amended to the HEAD commit, but only provided the HEAD
111 * commit is still the commit to be edited. When any other rebase
112 * command is processed, this file is deleted.
114 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
116 * When we stop at a given patch via the "edit" command, this file contains
117 * the abbreviated commit name of the corresponding patch.
119 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
121 * For the post-rewrite hook, we make a list of rewritten commits and
122 * their new sha1s. The rewritten-pending list keeps the sha1s of
123 * commits that have been processed, but not committed yet,
124 * e.g. because they are waiting for a 'squash' command.
126 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
127 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
128 "rebase-merge/rewritten-pending")
131 * The path of the file containig the OID of the "squash onto" commit, i.e.
132 * the dummy commit used for `reset [new root]`.
134 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
137 * The path of the file listing refs that need to be deleted after the rebase
138 * finishes. This is used by the `label` command to record the need for cleanup.
140 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
143 * The following files are written by git-rebase just after parsing the
144 * command-line (and are only consumed, not modified, by the sequencer).
146 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
147 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
148 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
149 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
150 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
151 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
152 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
153 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
154 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
155 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
157 static int git_sequencer_config(const char *k, const char *v, void *cb)
159 struct replay_opts *opts = cb;
160 int status;
162 if (!strcmp(k, "commit.cleanup")) {
163 const char *s;
165 status = git_config_string(&s, k, v);
166 if (status)
167 return status;
169 if (!strcmp(s, "verbatim"))
170 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
171 else if (!strcmp(s, "whitespace"))
172 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
173 else if (!strcmp(s, "strip"))
174 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
175 else if (!strcmp(s, "scissors"))
176 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
177 else
178 warning(_("invalid commit message cleanup mode '%s'"),
181 free((char *)s);
182 return status;
185 if (!strcmp(k, "commit.gpgsign")) {
186 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
187 return 0;
190 status = git_gpg_config(k, v, NULL);
191 if (status)
192 return status;
194 return git_diff_basic_config(k, v, NULL);
197 void sequencer_init_config(struct replay_opts *opts)
199 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
200 git_config(git_sequencer_config, opts);
203 static inline int is_rebase_i(const struct replay_opts *opts)
205 return opts->action == REPLAY_INTERACTIVE_REBASE;
208 static const char *get_dir(const struct replay_opts *opts)
210 if (is_rebase_i(opts))
211 return rebase_path();
212 return git_path_seq_dir();
215 static const char *get_todo_path(const struct replay_opts *opts)
217 if (is_rebase_i(opts))
218 return rebase_path_todo();
219 return git_path_todo_file();
223 * Returns 0 for non-conforming footer
224 * Returns 1 for conforming footer
225 * Returns 2 when sob exists within conforming footer
226 * Returns 3 when sob exists within conforming footer as last entry
228 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
229 size_t ignore_footer)
231 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
232 struct trailer_info info;
233 size_t i;
234 int found_sob = 0, found_sob_last = 0;
236 opts.no_divider = 1;
238 trailer_info_get(&info, sb->buf, &opts);
240 if (info.trailer_start == info.trailer_end)
241 return 0;
243 for (i = 0; i < info.trailer_nr; i++)
244 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
245 found_sob = 1;
246 if (i == info.trailer_nr - 1)
247 found_sob_last = 1;
250 trailer_info_release(&info);
252 if (found_sob_last)
253 return 3;
254 if (found_sob)
255 return 2;
256 return 1;
259 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
261 static struct strbuf buf = STRBUF_INIT;
263 strbuf_reset(&buf);
264 if (opts->gpg_sign)
265 sq_quotef(&buf, "-S%s", opts->gpg_sign);
266 return buf.buf;
269 int sequencer_remove_state(struct replay_opts *opts)
271 struct strbuf buf = STRBUF_INIT;
272 int i;
274 if (is_rebase_i(opts) &&
275 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
276 char *p = buf.buf;
277 while (*p) {
278 char *eol = strchr(p, '\n');
279 if (eol)
280 *eol = '\0';
281 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
282 warning(_("could not delete '%s'"), p);
283 if (!eol)
284 break;
285 p = eol + 1;
289 free(opts->gpg_sign);
290 free(opts->strategy);
291 for (i = 0; i < opts->xopts_nr; i++)
292 free(opts->xopts[i]);
293 free(opts->xopts);
294 strbuf_release(&opts->current_fixups);
296 strbuf_reset(&buf);
297 strbuf_addstr(&buf, get_dir(opts));
298 remove_dir_recursively(&buf, 0);
299 strbuf_release(&buf);
301 return 0;
304 static const char *action_name(const struct replay_opts *opts)
306 switch (opts->action) {
307 case REPLAY_REVERT:
308 return N_("revert");
309 case REPLAY_PICK:
310 return N_("cherry-pick");
311 case REPLAY_INTERACTIVE_REBASE:
312 return N_("rebase -i");
314 die(_("unknown action: %d"), opts->action);
317 struct commit_message {
318 char *parent_label;
319 char *label;
320 char *subject;
321 const char *message;
324 static const char *short_commit_name(struct commit *commit)
326 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
329 static int get_message(struct commit *commit, struct commit_message *out)
331 const char *abbrev, *subject;
332 int subject_len;
334 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
335 abbrev = short_commit_name(commit);
337 subject_len = find_commit_subject(out->message, &subject);
339 out->subject = xmemdupz(subject, subject_len);
340 out->label = xstrfmt("%s... %s", abbrev, out->subject);
341 out->parent_label = xstrfmt("parent of %s", out->label);
343 return 0;
346 static void free_message(struct commit *commit, struct commit_message *msg)
348 free(msg->parent_label);
349 free(msg->label);
350 free(msg->subject);
351 unuse_commit_buffer(commit, msg->message);
354 static void print_advice(int show_hint, struct replay_opts *opts)
356 char *msg = getenv("GIT_CHERRY_PICK_HELP");
358 if (msg) {
359 fprintf(stderr, "%s\n", msg);
361 * A conflict has occurred but the porcelain
362 * (typically rebase --interactive) wants to take care
363 * of the commit itself so remove CHERRY_PICK_HEAD
365 unlink(git_path_cherry_pick_head(the_repository));
366 return;
369 if (show_hint) {
370 if (opts->no_commit)
371 advise(_("after resolving the conflicts, mark the corrected paths\n"
372 "with 'git add <paths>' or 'git rm <paths>'"));
373 else
374 advise(_("after resolving the conflicts, mark the corrected paths\n"
375 "with 'git add <paths>' or 'git rm <paths>'\n"
376 "and commit the result with 'git commit'"));
380 static int write_message(const void *buf, size_t len, const char *filename,
381 int append_eol)
383 struct lock_file msg_file = LOCK_INIT;
385 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
386 if (msg_fd < 0)
387 return error_errno(_("could not lock '%s'"), filename);
388 if (write_in_full(msg_fd, buf, len) < 0) {
389 error_errno(_("could not write to '%s'"), filename);
390 rollback_lock_file(&msg_file);
391 return -1;
393 if (append_eol && write(msg_fd, "\n", 1) < 0) {
394 error_errno(_("could not write eol to '%s'"), filename);
395 rollback_lock_file(&msg_file);
396 return -1;
398 if (commit_lock_file(&msg_file) < 0)
399 return error(_("failed to finalize '%s'"), filename);
401 return 0;
405 * Reads a file that was presumably written by a shell script, i.e. with an
406 * end-of-line marker that needs to be stripped.
408 * Note that only the last end-of-line marker is stripped, consistent with the
409 * behavior of "$(cat path)" in a shell script.
411 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
413 static int read_oneliner(struct strbuf *buf,
414 const char *path, int skip_if_empty)
416 int orig_len = buf->len;
418 if (!file_exists(path))
419 return 0;
421 if (strbuf_read_file(buf, path, 0) < 0) {
422 warning_errno(_("could not read '%s'"), path);
423 return 0;
426 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
427 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
428 --buf->len;
429 buf->buf[buf->len] = '\0';
432 if (skip_if_empty && buf->len == orig_len)
433 return 0;
435 return 1;
438 static struct tree *empty_tree(void)
440 return lookup_tree(the_repository, the_repository->hash_algo->empty_tree);
443 static int error_dirty_index(struct replay_opts *opts)
445 if (read_cache_unmerged())
446 return error_resolve_conflict(_(action_name(opts)));
448 error(_("your local changes would be overwritten by %s."),
449 _(action_name(opts)));
451 if (advice_commit_before_merge)
452 advise(_("commit your changes or stash them to proceed."));
453 return -1;
456 static void update_abort_safety_file(void)
458 struct object_id head;
460 /* Do nothing on a single-pick */
461 if (!file_exists(git_path_seq_dir()))
462 return;
464 if (!get_oid("HEAD", &head))
465 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
466 else
467 write_file(git_path_abort_safety_file(), "%s", "");
470 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
471 int unborn, struct replay_opts *opts)
473 struct ref_transaction *transaction;
474 struct strbuf sb = STRBUF_INIT;
475 struct strbuf err = STRBUF_INIT;
477 read_cache();
478 if (checkout_fast_forward(from, to, 1))
479 return -1; /* the callee should have complained already */
481 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
483 transaction = ref_transaction_begin(&err);
484 if (!transaction ||
485 ref_transaction_update(transaction, "HEAD",
486 to, unborn && !is_rebase_i(opts) ?
487 &null_oid : from,
488 0, sb.buf, &err) ||
489 ref_transaction_commit(transaction, &err)) {
490 ref_transaction_free(transaction);
491 error("%s", err.buf);
492 strbuf_release(&sb);
493 strbuf_release(&err);
494 return -1;
497 strbuf_release(&sb);
498 strbuf_release(&err);
499 ref_transaction_free(transaction);
500 update_abort_safety_file();
501 return 0;
504 void append_conflicts_hint(struct strbuf *msgbuf)
506 int i;
508 strbuf_addch(msgbuf, '\n');
509 strbuf_commented_addf(msgbuf, "Conflicts:\n");
510 for (i = 0; i < active_nr;) {
511 const struct cache_entry *ce = active_cache[i++];
512 if (ce_stage(ce)) {
513 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
514 while (i < active_nr && !strcmp(ce->name,
515 active_cache[i]->name))
516 i++;
521 static int do_recursive_merge(struct commit *base, struct commit *next,
522 const char *base_label, const char *next_label,
523 struct object_id *head, struct strbuf *msgbuf,
524 struct replay_opts *opts)
526 struct merge_options o;
527 struct tree *result, *next_tree, *base_tree, *head_tree;
528 int clean;
529 char **xopt;
530 struct lock_file index_lock = LOCK_INIT;
532 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
533 return -1;
535 read_cache();
537 init_merge_options(&o);
538 o.ancestor = base ? base_label : "(empty tree)";
539 o.branch1 = "HEAD";
540 o.branch2 = next ? next_label : "(empty tree)";
541 if (is_rebase_i(opts))
542 o.buffer_output = 2;
543 o.show_rename_progress = 1;
545 head_tree = parse_tree_indirect(head);
546 next_tree = next ? get_commit_tree(next) : empty_tree();
547 base_tree = base ? get_commit_tree(base) : empty_tree();
549 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
550 parse_merge_opt(&o, *xopt);
552 clean = merge_trees(&o,
553 head_tree,
554 next_tree, base_tree, &result);
555 if (is_rebase_i(opts) && clean <= 0)
556 fputs(o.obuf.buf, stdout);
557 strbuf_release(&o.obuf);
558 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
559 if (clean < 0) {
560 rollback_lock_file(&index_lock);
561 return clean;
564 if (write_locked_index(&the_index, &index_lock,
565 COMMIT_LOCK | SKIP_IF_UNCHANGED))
567 * TRANSLATORS: %s will be "revert", "cherry-pick" or
568 * "rebase -i".
570 return error(_("%s: Unable to write new index file"),
571 _(action_name(opts)));
573 if (!clean)
574 append_conflicts_hint(msgbuf);
576 return !clean;
579 static struct object_id *get_cache_tree_oid(void)
581 if (!active_cache_tree)
582 active_cache_tree = cache_tree();
584 if (!cache_tree_fully_valid(active_cache_tree))
585 if (cache_tree_update(&the_index, 0)) {
586 error(_("unable to update cache tree"));
587 return NULL;
590 return &active_cache_tree->oid;
593 static int is_index_unchanged(void)
595 struct object_id head_oid, *cache_tree_oid;
596 struct commit *head_commit;
598 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
599 return error(_("could not resolve HEAD commit"));
601 head_commit = lookup_commit(the_repository, &head_oid);
604 * If head_commit is NULL, check_commit, called from
605 * lookup_commit, would have indicated that head_commit is not
606 * a commit object already. parse_commit() will return failure
607 * without further complaints in such a case. Otherwise, if
608 * the commit is invalid, parse_commit() will complain. So
609 * there is nothing for us to say here. Just return failure.
611 if (parse_commit(head_commit))
612 return -1;
614 if (!(cache_tree_oid = get_cache_tree_oid()))
615 return -1;
617 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
620 static int write_author_script(const char *message)
622 struct strbuf buf = STRBUF_INIT;
623 const char *eol;
624 int res;
626 for (;;)
627 if (!*message || starts_with(message, "\n")) {
628 missing_author:
629 /* Missing 'author' line? */
630 unlink(rebase_path_author_script());
631 return 0;
632 } else if (skip_prefix(message, "author ", &message))
633 break;
634 else if ((eol = strchr(message, '\n')))
635 message = eol + 1;
636 else
637 goto missing_author;
639 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
640 while (*message && *message != '\n' && *message != '\r')
641 if (skip_prefix(message, " <", &message))
642 break;
643 else if (*message != '\'')
644 strbuf_addch(&buf, *(message++));
645 else
646 strbuf_addf(&buf, "'\\%c'", *(message++));
647 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
648 while (*message && *message != '\n' && *message != '\r')
649 if (skip_prefix(message, "> ", &message))
650 break;
651 else if (*message != '\'')
652 strbuf_addch(&buf, *(message++));
653 else
654 strbuf_addf(&buf, "'\\%c'", *(message++));
655 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
656 while (*message && *message != '\n' && *message != '\r')
657 if (*message != '\'')
658 strbuf_addch(&buf, *(message++));
659 else
660 strbuf_addf(&buf, "'\\%c'", *(message++));
661 strbuf_addch(&buf, '\'');
662 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
663 strbuf_release(&buf);
664 return res;
669 * write_author_script() used to fail to terminate the last line with a "'" and
670 * also escaped "'" incorrectly as "'\\\\''" rather than "'\\''". We check for
671 * the terminating "'" on the last line to see how "'" has been escaped in case
672 * git was upgraded while rebase was stopped.
674 static int quoting_is_broken(const char *s, size_t n)
676 /* Skip any empty lines in case the file was hand edited */
677 while (n > 0 && s[--n] == '\n')
678 ; /* empty */
679 if (n > 0 && s[n] != '\'')
680 return 1;
682 return 0;
686 * Read a list of environment variable assignments (such as the author-script
687 * file) into an environment block. Returns -1 on error, 0 otherwise.
689 static int read_env_script(struct argv_array *env)
691 struct strbuf script = STRBUF_INIT;
692 int i, count = 0, sq_bug;
693 const char *p2;
694 char *p;
696 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
697 return -1;
698 /* write_author_script() used to quote incorrectly */
699 sq_bug = quoting_is_broken(script.buf, script.len);
700 for (p = script.buf; *p; p++)
701 if (sq_bug && skip_prefix(p, "'\\\\''", &p2))
702 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
703 else if (skip_prefix(p, "'\\''", &p2))
704 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
705 else if (*p == '\'')
706 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
707 else if (*p == '\n') {
708 *p = '\0';
709 count++;
712 for (i = 0, p = script.buf; i < count; i++) {
713 argv_array_push(env, p);
714 p += strlen(p) + 1;
717 return 0;
720 static char *get_author(const char *message)
722 size_t len;
723 const char *a;
725 a = find_commit_header(message, "author", &len);
726 if (a)
727 return xmemdupz(a, len);
729 return NULL;
732 /* Read author-script and return an ident line (author <email> timestamp) */
733 static const char *read_author_ident(struct strbuf *buf)
735 const char *keys[] = {
736 "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
738 struct strbuf out = STRBUF_INIT;
739 char *in, *eol;
740 const char *val[3];
741 int i = 0;
743 if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
744 return NULL;
746 /* dequote values and construct ident line in-place */
747 for (in = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
748 if (!skip_prefix(in, keys[i], (const char **)&in)) {
749 warning(_("could not parse '%s' (looking for '%s')"),
750 rebase_path_author_script(), keys[i]);
751 return NULL;
754 eol = strchrnul(in, '\n');
755 *eol = '\0';
756 if (!sq_dequote(in)) {
757 warning(_("bad quoting on %s value in '%s'"),
758 keys[i], rebase_path_author_script());
759 return NULL;
761 val[i] = in;
762 in = eol + 1;
765 if (i < 3) {
766 warning(_("could not parse '%s' (looking for '%s')"),
767 rebase_path_author_script(), keys[i]);
768 return NULL;
771 /* validate date since fmt_ident() will die() on bad value */
772 if (parse_date(val[2], &out)){
773 warning(_("invalid date format '%s' in '%s'"),
774 val[2], rebase_path_author_script());
775 strbuf_release(&out);
776 return NULL;
779 strbuf_reset(&out);
780 strbuf_addstr(&out, fmt_ident(val[0], val[1], val[2], 0));
781 strbuf_swap(buf, &out);
782 strbuf_release(&out);
783 return buf->buf;
786 static const char staged_changes_advice[] =
787 N_("you have staged changes in your working tree\n"
788 "If these changes are meant to be squashed into the previous commit, run:\n"
789 "\n"
790 " git commit --amend %s\n"
791 "\n"
792 "If they are meant to go into a new commit, run:\n"
793 "\n"
794 " git commit %s\n"
795 "\n"
796 "In both cases, once you're done, continue with:\n"
797 "\n"
798 " git rebase --continue\n");
800 #define ALLOW_EMPTY (1<<0)
801 #define EDIT_MSG (1<<1)
802 #define AMEND_MSG (1<<2)
803 #define CLEANUP_MSG (1<<3)
804 #define VERIFY_MSG (1<<4)
805 #define CREATE_ROOT_COMMIT (1<<5)
808 * If we are cherry-pick, and if the merge did not result in
809 * hand-editing, we will hit this commit and inherit the original
810 * author date and name.
812 * If we are revert, or if our cherry-pick results in a hand merge,
813 * we had better say that the current user is responsible for that.
815 * An exception is when run_git_commit() is called during an
816 * interactive rebase: in that case, we will want to retain the
817 * author metadata.
819 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
820 unsigned int flags)
822 struct child_process cmd = CHILD_PROCESS_INIT;
823 const char *value;
825 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
826 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
827 const char *author = NULL;
828 struct object_id root_commit, *cache_tree_oid;
829 int res = 0;
831 if (is_rebase_i(opts)) {
832 author = read_author_ident(&script);
833 if (!author) {
834 strbuf_release(&script);
835 return -1;
839 if (!defmsg)
840 BUG("root commit without message");
842 if (!(cache_tree_oid = get_cache_tree_oid()))
843 res = -1;
845 if (!res)
846 res = strbuf_read_file(&msg, defmsg, 0);
848 if (res <= 0)
849 res = error_errno(_("could not read '%s'"), defmsg);
850 else
851 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
852 NULL, &root_commit, author,
853 opts->gpg_sign);
855 strbuf_release(&msg);
856 strbuf_release(&script);
857 if (!res) {
858 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
859 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
860 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
861 UPDATE_REFS_MSG_ON_ERR);
863 return res < 0 ? error(_("writing root commit")) : 0;
866 cmd.git_cmd = 1;
868 if (is_rebase_i(opts)) {
869 if (!(flags & EDIT_MSG)) {
870 cmd.stdout_to_stderr = 1;
871 cmd.err = -1;
874 if (read_env_script(&cmd.env_array)) {
875 const char *gpg_opt = gpg_sign_opt_quoted(opts);
877 return error(_(staged_changes_advice),
878 gpg_opt, gpg_opt);
882 argv_array_push(&cmd.args, "commit");
884 if (!(flags & VERIFY_MSG))
885 argv_array_push(&cmd.args, "-n");
886 if ((flags & AMEND_MSG))
887 argv_array_push(&cmd.args, "--amend");
888 if (opts->gpg_sign)
889 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
890 if (defmsg)
891 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
892 else if (!(flags & EDIT_MSG))
893 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
894 if ((flags & CLEANUP_MSG))
895 argv_array_push(&cmd.args, "--cleanup=strip");
896 if ((flags & EDIT_MSG))
897 argv_array_push(&cmd.args, "-e");
898 else if (!(flags & CLEANUP_MSG) &&
899 !opts->signoff && !opts->record_origin &&
900 git_config_get_value("commit.cleanup", &value))
901 argv_array_push(&cmd.args, "--cleanup=verbatim");
903 if ((flags & ALLOW_EMPTY))
904 argv_array_push(&cmd.args, "--allow-empty");
906 if (opts->allow_empty_message)
907 argv_array_push(&cmd.args, "--allow-empty-message");
909 if (cmd.err == -1) {
910 /* hide stderr on success */
911 struct strbuf buf = STRBUF_INIT;
912 int rc = pipe_command(&cmd,
913 NULL, 0,
914 /* stdout is already redirected */
915 NULL, 0,
916 &buf, 0);
917 if (rc)
918 fputs(buf.buf, stderr);
919 strbuf_release(&buf);
920 return rc;
923 return run_command(&cmd);
926 static int rest_is_empty(const struct strbuf *sb, int start)
928 int i, eol;
929 const char *nl;
931 /* Check if the rest is just whitespace and Signed-off-by's. */
932 for (i = start; i < sb->len; i++) {
933 nl = memchr(sb->buf + i, '\n', sb->len - i);
934 if (nl)
935 eol = nl - sb->buf;
936 else
937 eol = sb->len;
939 if (strlen(sign_off_header) <= eol - i &&
940 starts_with(sb->buf + i, sign_off_header)) {
941 i = eol;
942 continue;
944 while (i < eol)
945 if (!isspace(sb->buf[i++]))
946 return 0;
949 return 1;
953 * Find out if the message in the strbuf contains only whitespace and
954 * Signed-off-by lines.
956 int message_is_empty(const struct strbuf *sb,
957 enum commit_msg_cleanup_mode cleanup_mode)
959 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
960 return 0;
961 return rest_is_empty(sb, 0);
965 * See if the user edited the message in the editor or left what
966 * was in the template intact
968 int template_untouched(const struct strbuf *sb, const char *template_file,
969 enum commit_msg_cleanup_mode cleanup_mode)
971 struct strbuf tmpl = STRBUF_INIT;
972 const char *start;
974 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
975 return 0;
977 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
978 return 0;
980 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
981 if (!skip_prefix(sb->buf, tmpl.buf, &start))
982 start = sb->buf;
983 strbuf_release(&tmpl);
984 return rest_is_empty(sb, start - sb->buf);
987 int update_head_with_reflog(const struct commit *old_head,
988 const struct object_id *new_head,
989 const char *action, const struct strbuf *msg,
990 struct strbuf *err)
992 struct ref_transaction *transaction;
993 struct strbuf sb = STRBUF_INIT;
994 const char *nl;
995 int ret = 0;
997 if (action) {
998 strbuf_addstr(&sb, action);
999 strbuf_addstr(&sb, ": ");
1002 nl = strchr(msg->buf, '\n');
1003 if (nl) {
1004 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1005 } else {
1006 strbuf_addbuf(&sb, msg);
1007 strbuf_addch(&sb, '\n');
1010 transaction = ref_transaction_begin(err);
1011 if (!transaction ||
1012 ref_transaction_update(transaction, "HEAD", new_head,
1013 old_head ? &old_head->object.oid : &null_oid,
1014 0, sb.buf, err) ||
1015 ref_transaction_commit(transaction, err)) {
1016 ret = -1;
1018 ref_transaction_free(transaction);
1019 strbuf_release(&sb);
1021 return ret;
1024 static int run_rewrite_hook(const struct object_id *oldoid,
1025 const struct object_id *newoid)
1027 struct child_process proc = CHILD_PROCESS_INIT;
1028 const char *argv[3];
1029 int code;
1030 struct strbuf sb = STRBUF_INIT;
1032 argv[0] = find_hook("post-rewrite");
1033 if (!argv[0])
1034 return 0;
1036 argv[1] = "amend";
1037 argv[2] = NULL;
1039 proc.argv = argv;
1040 proc.in = -1;
1041 proc.stdout_to_stderr = 1;
1043 code = start_command(&proc);
1044 if (code)
1045 return code;
1046 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1047 sigchain_push(SIGPIPE, SIG_IGN);
1048 write_in_full(proc.in, sb.buf, sb.len);
1049 close(proc.in);
1050 strbuf_release(&sb);
1051 sigchain_pop(SIGPIPE);
1052 return finish_command(&proc);
1055 void commit_post_rewrite(const struct commit *old_head,
1056 const struct object_id *new_head)
1058 struct notes_rewrite_cfg *cfg;
1060 cfg = init_copy_notes_for_rewrite("amend");
1061 if (cfg) {
1062 /* we are amending, so old_head is not NULL */
1063 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1064 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1066 run_rewrite_hook(&old_head->object.oid, new_head);
1069 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1071 struct argv_array hook_env = ARGV_ARRAY_INIT;
1072 int ret;
1073 const char *name;
1075 name = git_path_commit_editmsg();
1076 if (write_message(msg->buf, msg->len, name, 0))
1077 return -1;
1079 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1080 argv_array_push(&hook_env, "GIT_EDITOR=:");
1081 if (commit)
1082 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1083 "commit", commit, NULL);
1084 else
1085 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1086 "message", NULL);
1087 if (ret)
1088 ret = error(_("'prepare-commit-msg' hook failed"));
1089 argv_array_clear(&hook_env);
1091 return ret;
1094 static const char implicit_ident_advice_noconfig[] =
1095 N_("Your name and email address were configured automatically based\n"
1096 "on your username and hostname. Please check that they are accurate.\n"
1097 "You can suppress this message by setting them explicitly. Run the\n"
1098 "following command and follow the instructions in your editor to edit\n"
1099 "your configuration file:\n"
1100 "\n"
1101 " git config --global --edit\n"
1102 "\n"
1103 "After doing this, you may fix the identity used for this commit with:\n"
1104 "\n"
1105 " git commit --amend --reset-author\n");
1107 static const char implicit_ident_advice_config[] =
1108 N_("Your name and email address were configured automatically based\n"
1109 "on your username and hostname. Please check that they are accurate.\n"
1110 "You can suppress this message by setting them explicitly:\n"
1111 "\n"
1112 " git config --global user.name \"Your Name\"\n"
1113 " git config --global user.email you@example.com\n"
1114 "\n"
1115 "After doing this, you may fix the identity used for this commit with:\n"
1116 "\n"
1117 " git commit --amend --reset-author\n");
1119 static const char *implicit_ident_advice(void)
1121 char *user_config = expand_user_path("~/.gitconfig", 0);
1122 char *xdg_config = xdg_config_home("config");
1123 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1125 free(user_config);
1126 free(xdg_config);
1128 if (config_exists)
1129 return _(implicit_ident_advice_config);
1130 else
1131 return _(implicit_ident_advice_noconfig);
1135 void print_commit_summary(const char *prefix, const struct object_id *oid,
1136 unsigned int flags)
1138 struct rev_info rev;
1139 struct commit *commit;
1140 struct strbuf format = STRBUF_INIT;
1141 const char *head;
1142 struct pretty_print_context pctx = {0};
1143 struct strbuf author_ident = STRBUF_INIT;
1144 struct strbuf committer_ident = STRBUF_INIT;
1146 commit = lookup_commit(the_repository, oid);
1147 if (!commit)
1148 die(_("couldn't look up newly created commit"));
1149 if (parse_commit(commit))
1150 die(_("could not parse newly created commit"));
1152 strbuf_addstr(&format, "format:%h] %s");
1154 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1155 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1156 if (strbuf_cmp(&author_ident, &committer_ident)) {
1157 strbuf_addstr(&format, "\n Author: ");
1158 strbuf_addbuf_percentquote(&format, &author_ident);
1160 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1161 struct strbuf date = STRBUF_INIT;
1163 format_commit_message(commit, "%ad", &date, &pctx);
1164 strbuf_addstr(&format, "\n Date: ");
1165 strbuf_addbuf_percentquote(&format, &date);
1166 strbuf_release(&date);
1168 if (!committer_ident_sufficiently_given()) {
1169 strbuf_addstr(&format, "\n Committer: ");
1170 strbuf_addbuf_percentquote(&format, &committer_ident);
1171 if (advice_implicit_identity) {
1172 strbuf_addch(&format, '\n');
1173 strbuf_addstr(&format, implicit_ident_advice());
1176 strbuf_release(&author_ident);
1177 strbuf_release(&committer_ident);
1179 init_revisions(&rev, prefix);
1180 setup_revisions(0, NULL, &rev, NULL);
1182 rev.diff = 1;
1183 rev.diffopt.output_format =
1184 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1186 rev.verbose_header = 1;
1187 rev.show_root_diff = 1;
1188 get_commit_format(format.buf, &rev);
1189 rev.always_show_header = 0;
1190 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1191 rev.diffopt.break_opt = 0;
1192 diff_setup_done(&rev.diffopt);
1194 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1195 if (!head)
1196 die_errno(_("unable to resolve HEAD after creating commit"));
1197 if (!strcmp(head, "HEAD"))
1198 head = _("detached HEAD");
1199 else
1200 skip_prefix(head, "refs/heads/", &head);
1201 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1202 _(" (root-commit)") : "");
1204 if (!log_tree_commit(&rev, commit)) {
1205 rev.always_show_header = 1;
1206 rev.use_terminator = 1;
1207 log_tree_commit(&rev, commit);
1210 strbuf_release(&format);
1213 static int parse_head(struct commit **head)
1215 struct commit *current_head;
1216 struct object_id oid;
1218 if (get_oid("HEAD", &oid)) {
1219 current_head = NULL;
1220 } else {
1221 current_head = lookup_commit_reference(the_repository, &oid);
1222 if (!current_head)
1223 return error(_("could not parse HEAD"));
1224 if (!oideq(&oid, &current_head->object.oid)) {
1225 warning(_("HEAD %s is not a commit!"),
1226 oid_to_hex(&oid));
1228 if (parse_commit(current_head))
1229 return error(_("could not parse HEAD commit"));
1231 *head = current_head;
1233 return 0;
1237 * Try to commit without forking 'git commit'. In some cases we need
1238 * to run 'git commit' to display an error message
1240 * Returns:
1241 * -1 - error unable to commit
1242 * 0 - success
1243 * 1 - run 'git commit'
1245 static int try_to_commit(struct strbuf *msg, const char *author,
1246 struct replay_opts *opts, unsigned int flags,
1247 struct object_id *oid)
1249 struct object_id tree;
1250 struct commit *current_head;
1251 struct commit_list *parents = NULL;
1252 struct commit_extra_header *extra = NULL;
1253 struct strbuf err = STRBUF_INIT;
1254 struct strbuf commit_msg = STRBUF_INIT;
1255 char *amend_author = NULL;
1256 const char *hook_commit = NULL;
1257 enum commit_msg_cleanup_mode cleanup;
1258 int res = 0;
1260 if (parse_head(&current_head))
1261 return -1;
1263 if (flags & AMEND_MSG) {
1264 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1265 const char *out_enc = get_commit_output_encoding();
1266 const char *message = logmsg_reencode(current_head, NULL,
1267 out_enc);
1269 if (!msg) {
1270 const char *orig_message = NULL;
1272 find_commit_subject(message, &orig_message);
1273 msg = &commit_msg;
1274 strbuf_addstr(msg, orig_message);
1275 hook_commit = "HEAD";
1277 author = amend_author = get_author(message);
1278 unuse_commit_buffer(current_head, message);
1279 if (!author) {
1280 res = error(_("unable to parse commit author"));
1281 goto out;
1283 parents = copy_commit_list(current_head->parents);
1284 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1285 } else if (current_head) {
1286 commit_list_insert(current_head, &parents);
1289 if (write_index_as_tree(&tree, &the_index, get_index_file(), 0, NULL)) {
1290 res = error(_("git write-tree failed to write a tree"));
1291 goto out;
1294 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1295 get_commit_tree_oid(current_head) :
1296 the_hash_algo->empty_tree, &tree)) {
1297 res = 1; /* run 'git commit' to display error message */
1298 goto out;
1301 if (find_hook("prepare-commit-msg")) {
1302 res = run_prepare_commit_msg_hook(msg, hook_commit);
1303 if (res)
1304 goto out;
1305 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1306 2048) < 0) {
1307 res = error_errno(_("unable to read commit message "
1308 "from '%s'"),
1309 git_path_commit_editmsg());
1310 goto out;
1312 msg = &commit_msg;
1315 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1316 opts->default_msg_cleanup;
1318 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1319 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1320 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1321 res = 1; /* run 'git commit' to display error message */
1322 goto out;
1325 reset_ident_date();
1327 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1328 oid, author, opts->gpg_sign, extra)) {
1329 res = error(_("failed to write commit object"));
1330 goto out;
1333 if (update_head_with_reflog(current_head, oid,
1334 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1335 res = error("%s", err.buf);
1336 goto out;
1339 if (flags & AMEND_MSG)
1340 commit_post_rewrite(current_head, oid);
1342 out:
1343 free_commit_extra_headers(extra);
1344 strbuf_release(&err);
1345 strbuf_release(&commit_msg);
1346 free(amend_author);
1348 return res;
1351 static int do_commit(const char *msg_file, const char *author,
1352 struct replay_opts *opts, unsigned int flags)
1354 int res = 1;
1356 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1357 !(flags & CREATE_ROOT_COMMIT)) {
1358 struct object_id oid;
1359 struct strbuf sb = STRBUF_INIT;
1361 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1362 return error_errno(_("unable to read commit message "
1363 "from '%s'"),
1364 msg_file);
1366 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1367 &oid);
1368 strbuf_release(&sb);
1369 if (!res) {
1370 unlink(git_path_cherry_pick_head(the_repository));
1371 unlink(git_path_merge_msg(the_repository));
1372 if (!is_rebase_i(opts))
1373 print_commit_summary(NULL, &oid,
1374 SUMMARY_SHOW_AUTHOR_DATE);
1375 return res;
1378 if (res == 1)
1379 return run_git_commit(msg_file, opts, flags);
1381 return res;
1384 static int is_original_commit_empty(struct commit *commit)
1386 const struct object_id *ptree_oid;
1388 if (parse_commit(commit))
1389 return error(_("could not parse commit %s"),
1390 oid_to_hex(&commit->object.oid));
1391 if (commit->parents) {
1392 struct commit *parent = commit->parents->item;
1393 if (parse_commit(parent))
1394 return error(_("could not parse parent commit %s"),
1395 oid_to_hex(&parent->object.oid));
1396 ptree_oid = get_commit_tree_oid(parent);
1397 } else {
1398 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1401 return oideq(ptree_oid, get_commit_tree_oid(commit));
1405 * Do we run "git commit" with "--allow-empty"?
1407 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1409 int index_unchanged, empty_commit;
1412 * Three cases:
1414 * (1) we do not allow empty at all and error out.
1416 * (2) we allow ones that were initially empty, but
1417 * forbid the ones that become empty;
1419 * (3) we allow both.
1421 if (!opts->allow_empty)
1422 return 0; /* let "git commit" barf as necessary */
1424 index_unchanged = is_index_unchanged();
1425 if (index_unchanged < 0)
1426 return index_unchanged;
1427 if (!index_unchanged)
1428 return 0; /* we do not have to say --allow-empty */
1430 if (opts->keep_redundant_commits)
1431 return 1;
1433 empty_commit = is_original_commit_empty(commit);
1434 if (empty_commit < 0)
1435 return empty_commit;
1436 if (!empty_commit)
1437 return 0;
1438 else
1439 return 1;
1443 * Note that ordering matters in this enum. Not only must it match the mapping
1444 * below, it is also divided into several sections that matter. When adding
1445 * new commands, make sure you add it in the right section.
1447 enum todo_command {
1448 /* commands that handle commits */
1449 TODO_PICK = 0,
1450 TODO_REVERT,
1451 TODO_EDIT,
1452 TODO_REWORD,
1453 TODO_FIXUP,
1454 TODO_SQUASH,
1455 /* commands that do something else than handling a single commit */
1456 TODO_EXEC,
1457 TODO_LABEL,
1458 TODO_RESET,
1459 TODO_MERGE,
1460 /* commands that do nothing but are counted for reporting progress */
1461 TODO_NOOP,
1462 TODO_DROP,
1463 /* comments (not counted for reporting progress) */
1464 TODO_COMMENT
1467 static struct {
1468 char c;
1469 const char *str;
1470 } todo_command_info[] = {
1471 { 'p', "pick" },
1472 { 0, "revert" },
1473 { 'e', "edit" },
1474 { 'r', "reword" },
1475 { 'f', "fixup" },
1476 { 's', "squash" },
1477 { 'x', "exec" },
1478 { 'l', "label" },
1479 { 't', "reset" },
1480 { 'm', "merge" },
1481 { 0, "noop" },
1482 { 'd', "drop" },
1483 { 0, NULL }
1486 static const char *command_to_string(const enum todo_command command)
1488 if (command < TODO_COMMENT)
1489 return todo_command_info[command].str;
1490 die(_("unknown command: %d"), command);
1493 static char command_to_char(const enum todo_command command)
1495 if (command < TODO_COMMENT && todo_command_info[command].c)
1496 return todo_command_info[command].c;
1497 return comment_line_char;
1500 static int is_noop(const enum todo_command command)
1502 return TODO_NOOP <= command;
1505 static int is_fixup(enum todo_command command)
1507 return command == TODO_FIXUP || command == TODO_SQUASH;
1510 /* Does this command create a (non-merge) commit? */
1511 static int is_pick_or_similar(enum todo_command command)
1513 switch (command) {
1514 case TODO_PICK:
1515 case TODO_REVERT:
1516 case TODO_EDIT:
1517 case TODO_REWORD:
1518 case TODO_FIXUP:
1519 case TODO_SQUASH:
1520 return 1;
1521 default:
1522 return 0;
1526 static int update_squash_messages(enum todo_command command,
1527 struct commit *commit, struct replay_opts *opts)
1529 struct strbuf buf = STRBUF_INIT;
1530 int res;
1531 const char *message, *body;
1533 if (opts->current_fixup_count > 0) {
1534 struct strbuf header = STRBUF_INIT;
1535 char *eol;
1537 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1538 return error(_("could not read '%s'"),
1539 rebase_path_squash_msg());
1541 eol = buf.buf[0] != comment_line_char ?
1542 buf.buf : strchrnul(buf.buf, '\n');
1544 strbuf_addf(&header, "%c ", comment_line_char);
1545 strbuf_addf(&header, _("This is a combination of %d commits."),
1546 opts->current_fixup_count + 2);
1547 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1548 strbuf_release(&header);
1549 } else {
1550 struct object_id head;
1551 struct commit *head_commit;
1552 const char *head_message, *body;
1554 if (get_oid("HEAD", &head))
1555 return error(_("need a HEAD to fixup"));
1556 if (!(head_commit = lookup_commit_reference(the_repository, &head)))
1557 return error(_("could not read HEAD"));
1558 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1559 return error(_("could not read HEAD's commit message"));
1561 find_commit_subject(head_message, &body);
1562 if (write_message(body, strlen(body),
1563 rebase_path_fixup_msg(), 0)) {
1564 unuse_commit_buffer(head_commit, head_message);
1565 return error(_("cannot write '%s'"),
1566 rebase_path_fixup_msg());
1569 strbuf_addf(&buf, "%c ", comment_line_char);
1570 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1571 strbuf_addf(&buf, "\n%c ", comment_line_char);
1572 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1573 strbuf_addstr(&buf, "\n\n");
1574 strbuf_addstr(&buf, body);
1576 unuse_commit_buffer(head_commit, head_message);
1579 if (!(message = get_commit_buffer(commit, NULL)))
1580 return error(_("could not read commit message of %s"),
1581 oid_to_hex(&commit->object.oid));
1582 find_commit_subject(message, &body);
1584 if (command == TODO_SQUASH) {
1585 unlink(rebase_path_fixup_msg());
1586 strbuf_addf(&buf, "\n%c ", comment_line_char);
1587 strbuf_addf(&buf, _("This is the commit message #%d:"),
1588 ++opts->current_fixup_count + 1);
1589 strbuf_addstr(&buf, "\n\n");
1590 strbuf_addstr(&buf, body);
1591 } else if (command == TODO_FIXUP) {
1592 strbuf_addf(&buf, "\n%c ", comment_line_char);
1593 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1594 ++opts->current_fixup_count + 1);
1595 strbuf_addstr(&buf, "\n\n");
1596 strbuf_add_commented_lines(&buf, body, strlen(body));
1597 } else
1598 return error(_("unknown command: %d"), command);
1599 unuse_commit_buffer(commit, message);
1601 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1602 strbuf_release(&buf);
1604 if (!res) {
1605 strbuf_addf(&opts->current_fixups, "%s%s %s",
1606 opts->current_fixups.len ? "\n" : "",
1607 command_to_string(command),
1608 oid_to_hex(&commit->object.oid));
1609 res = write_message(opts->current_fixups.buf,
1610 opts->current_fixups.len,
1611 rebase_path_current_fixups(), 0);
1614 return res;
1617 static void flush_rewritten_pending(void) {
1618 struct strbuf buf = STRBUF_INIT;
1619 struct object_id newoid;
1620 FILE *out;
1622 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1623 !get_oid("HEAD", &newoid) &&
1624 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1625 char *bol = buf.buf, *eol;
1627 while (*bol) {
1628 eol = strchrnul(bol, '\n');
1629 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1630 bol, oid_to_hex(&newoid));
1631 if (!*eol)
1632 break;
1633 bol = eol + 1;
1635 fclose(out);
1636 unlink(rebase_path_rewritten_pending());
1638 strbuf_release(&buf);
1641 static void record_in_rewritten(struct object_id *oid,
1642 enum todo_command next_command) {
1643 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1645 if (!out)
1646 return;
1648 fprintf(out, "%s\n", oid_to_hex(oid));
1649 fclose(out);
1651 if (!is_fixup(next_command))
1652 flush_rewritten_pending();
1655 static int do_pick_commit(enum todo_command command, struct commit *commit,
1656 struct replay_opts *opts, int final_fixup)
1658 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1659 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(the_repository);
1660 struct object_id head;
1661 struct commit *base, *next, *parent;
1662 const char *base_label, *next_label;
1663 char *author = NULL;
1664 struct commit_message msg = { NULL, NULL, NULL, NULL };
1665 struct strbuf msgbuf = STRBUF_INIT;
1666 int res, unborn = 0, allow;
1668 if (opts->no_commit) {
1670 * We do not intend to commit immediately. We just want to
1671 * merge the differences in, so let's compute the tree
1672 * that represents the "current" state for merge-recursive
1673 * to work on.
1675 if (write_index_as_tree(&head, &the_index, get_index_file(), 0, NULL))
1676 return error(_("your index file is unmerged."));
1677 } else {
1678 unborn = get_oid("HEAD", &head);
1679 /* Do we want to generate a root commit? */
1680 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1681 oideq(&head, &opts->squash_onto)) {
1682 if (is_fixup(command))
1683 return error(_("cannot fixup root commit"));
1684 flags |= CREATE_ROOT_COMMIT;
1685 unborn = 1;
1686 } else if (unborn)
1687 oidcpy(&head, the_hash_algo->empty_tree);
1688 if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
1689 NULL, 0))
1690 return error_dirty_index(opts);
1692 discard_cache();
1694 if (!commit->parents)
1695 parent = NULL;
1696 else if (commit->parents->next) {
1697 /* Reverting or cherry-picking a merge commit */
1698 int cnt;
1699 struct commit_list *p;
1701 if (!opts->mainline)
1702 return error(_("commit %s is a merge but no -m option was given."),
1703 oid_to_hex(&commit->object.oid));
1705 for (cnt = 1, p = commit->parents;
1706 cnt != opts->mainline && p;
1707 cnt++)
1708 p = p->next;
1709 if (cnt != opts->mainline || !p)
1710 return error(_("commit %s does not have parent %d"),
1711 oid_to_hex(&commit->object.oid), opts->mainline);
1712 parent = p->item;
1713 } else if (0 < opts->mainline)
1714 return error(_("mainline was specified but commit %s is not a merge."),
1715 oid_to_hex(&commit->object.oid));
1716 else
1717 parent = commit->parents->item;
1719 if (get_message(commit, &msg) != 0)
1720 return error(_("cannot get commit message for %s"),
1721 oid_to_hex(&commit->object.oid));
1723 if (opts->allow_ff && !is_fixup(command) &&
1724 ((parent && oideq(&parent->object.oid, &head)) ||
1725 (!parent && unborn))) {
1726 if (is_rebase_i(opts))
1727 write_author_script(msg.message);
1728 res = fast_forward_to(&commit->object.oid, &head, unborn,
1729 opts);
1730 if (res || command != TODO_REWORD)
1731 goto leave;
1732 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1733 msg_file = NULL;
1734 goto fast_forward_edit;
1736 if (parent && parse_commit(parent) < 0)
1737 /* TRANSLATORS: The first %s will be a "todo" command like
1738 "revert" or "pick", the second %s a SHA1. */
1739 return error(_("%s: cannot parse parent commit %s"),
1740 command_to_string(command),
1741 oid_to_hex(&parent->object.oid));
1744 * "commit" is an existing commit. We would want to apply
1745 * the difference it introduces since its first parent "prev"
1746 * on top of the current HEAD if we are cherry-pick. Or the
1747 * reverse of it if we are revert.
1750 if (command == TODO_REVERT) {
1751 base = commit;
1752 base_label = msg.label;
1753 next = parent;
1754 next_label = msg.parent_label;
1755 strbuf_addstr(&msgbuf, "Revert \"");
1756 strbuf_addstr(&msgbuf, msg.subject);
1757 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1758 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1760 if (commit->parents && commit->parents->next) {
1761 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1762 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1764 strbuf_addstr(&msgbuf, ".\n");
1765 } else {
1766 const char *p;
1768 base = parent;
1769 base_label = msg.parent_label;
1770 next = commit;
1771 next_label = msg.label;
1773 /* Append the commit log message to msgbuf. */
1774 if (find_commit_subject(msg.message, &p))
1775 strbuf_addstr(&msgbuf, p);
1777 if (opts->record_origin) {
1778 strbuf_complete_line(&msgbuf);
1779 if (!has_conforming_footer(&msgbuf, NULL, 0))
1780 strbuf_addch(&msgbuf, '\n');
1781 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1782 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1783 strbuf_addstr(&msgbuf, ")\n");
1785 if (!is_fixup(command))
1786 author = get_author(msg.message);
1789 if (command == TODO_REWORD)
1790 flags |= EDIT_MSG | VERIFY_MSG;
1791 else if (is_fixup(command)) {
1792 if (update_squash_messages(command, commit, opts))
1793 return -1;
1794 flags |= AMEND_MSG;
1795 if (!final_fixup)
1796 msg_file = rebase_path_squash_msg();
1797 else if (file_exists(rebase_path_fixup_msg())) {
1798 flags |= CLEANUP_MSG;
1799 msg_file = rebase_path_fixup_msg();
1800 } else {
1801 const char *dest = git_path_squash_msg(the_repository);
1802 unlink(dest);
1803 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1804 return error(_("could not rename '%s' to '%s'"),
1805 rebase_path_squash_msg(), dest);
1806 unlink(git_path_merge_msg(the_repository));
1807 msg_file = dest;
1808 flags |= EDIT_MSG;
1812 if (opts->signoff && !is_fixup(command))
1813 append_signoff(&msgbuf, 0, 0);
1815 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1816 res = -1;
1817 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1818 res = do_recursive_merge(base, next, base_label, next_label,
1819 &head, &msgbuf, opts);
1820 if (res < 0)
1821 goto leave;
1823 res |= write_message(msgbuf.buf, msgbuf.len,
1824 git_path_merge_msg(the_repository), 0);
1825 } else {
1826 struct commit_list *common = NULL;
1827 struct commit_list *remotes = NULL;
1829 res = write_message(msgbuf.buf, msgbuf.len,
1830 git_path_merge_msg(the_repository), 0);
1832 commit_list_insert(base, &common);
1833 commit_list_insert(next, &remotes);
1834 res |= try_merge_command(opts->strategy,
1835 opts->xopts_nr, (const char **)opts->xopts,
1836 common, oid_to_hex(&head), remotes);
1837 free_commit_list(common);
1838 free_commit_list(remotes);
1840 strbuf_release(&msgbuf);
1843 * If the merge was clean or if it failed due to conflict, we write
1844 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1845 * However, if the merge did not even start, then we don't want to
1846 * write it at all.
1848 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1849 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1850 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1851 res = -1;
1852 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1853 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1854 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1855 res = -1;
1857 if (res) {
1858 error(command == TODO_REVERT
1859 ? _("could not revert %s... %s")
1860 : _("could not apply %s... %s"),
1861 short_commit_name(commit), msg.subject);
1862 print_advice(res == 1, opts);
1863 rerere(opts->allow_rerere_auto);
1864 goto leave;
1867 allow = allow_empty(opts, commit);
1868 if (allow < 0) {
1869 res = allow;
1870 goto leave;
1871 } else if (allow)
1872 flags |= ALLOW_EMPTY;
1873 if (!opts->no_commit) {
1874 fast_forward_edit:
1875 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1876 res = do_commit(msg_file, author, opts, flags);
1877 else
1878 res = error(_("unable to parse commit author"));
1881 if (!res && final_fixup) {
1882 unlink(rebase_path_fixup_msg());
1883 unlink(rebase_path_squash_msg());
1884 unlink(rebase_path_current_fixups());
1885 strbuf_reset(&opts->current_fixups);
1886 opts->current_fixup_count = 0;
1889 leave:
1890 free_message(commit, &msg);
1891 free(author);
1892 update_abort_safety_file();
1894 return res;
1897 static int prepare_revs(struct replay_opts *opts)
1900 * picking (but not reverting) ranges (but not individual revisions)
1901 * should be done in reverse
1903 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1904 opts->revs->reverse ^= 1;
1906 if (prepare_revision_walk(opts->revs))
1907 return error(_("revision walk setup failed"));
1909 return 0;
1912 static int read_and_refresh_cache(struct replay_opts *opts)
1914 struct lock_file index_lock = LOCK_INIT;
1915 int index_fd = hold_locked_index(&index_lock, 0);
1916 if (read_index_preload(&the_index, NULL) < 0) {
1917 rollback_lock_file(&index_lock);
1918 return error(_("git %s: failed to read the index"),
1919 _(action_name(opts)));
1921 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1922 if (index_fd >= 0) {
1923 if (write_locked_index(&the_index, &index_lock,
1924 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1925 return error(_("git %s: failed to refresh the index"),
1926 _(action_name(opts)));
1929 return 0;
1932 enum todo_item_flags {
1933 TODO_EDIT_MERGE_MSG = 1
1936 struct todo_item {
1937 enum todo_command command;
1938 struct commit *commit;
1939 unsigned int flags;
1940 const char *arg;
1941 int arg_len;
1942 size_t offset_in_buf;
1945 struct todo_list {
1946 struct strbuf buf;
1947 struct todo_item *items;
1948 int nr, alloc, current;
1949 int done_nr, total_nr;
1950 struct stat_data stat;
1953 #define TODO_LIST_INIT { STRBUF_INIT }
1955 static void todo_list_release(struct todo_list *todo_list)
1957 strbuf_release(&todo_list->buf);
1958 FREE_AND_NULL(todo_list->items);
1959 todo_list->nr = todo_list->alloc = 0;
1962 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1964 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1965 return todo_list->items + todo_list->nr++;
1968 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1970 struct object_id commit_oid;
1971 char *end_of_object_name;
1972 int i, saved, status, padding;
1974 item->flags = 0;
1976 /* left-trim */
1977 bol += strspn(bol, " \t");
1979 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1980 item->command = TODO_COMMENT;
1981 item->commit = NULL;
1982 item->arg = bol;
1983 item->arg_len = eol - bol;
1984 return 0;
1987 for (i = 0; i < TODO_COMMENT; i++)
1988 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1989 item->command = i;
1990 break;
1991 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1992 bol++;
1993 item->command = i;
1994 break;
1996 if (i >= TODO_COMMENT)
1997 return -1;
1999 /* Eat up extra spaces/ tabs before object name */
2000 padding = strspn(bol, " \t");
2001 bol += padding;
2003 if (item->command == TODO_NOOP) {
2004 if (bol != eol)
2005 return error(_("%s does not accept arguments: '%s'"),
2006 command_to_string(item->command), bol);
2007 item->commit = NULL;
2008 item->arg = bol;
2009 item->arg_len = eol - bol;
2010 return 0;
2013 if (!padding)
2014 return error(_("missing arguments for %s"),
2015 command_to_string(item->command));
2017 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2018 item->command == TODO_RESET) {
2019 item->commit = NULL;
2020 item->arg = bol;
2021 item->arg_len = (int)(eol - bol);
2022 return 0;
2025 if (item->command == TODO_MERGE) {
2026 if (skip_prefix(bol, "-C", &bol))
2027 bol += strspn(bol, " \t");
2028 else if (skip_prefix(bol, "-c", &bol)) {
2029 bol += strspn(bol, " \t");
2030 item->flags |= TODO_EDIT_MERGE_MSG;
2031 } else {
2032 item->flags |= TODO_EDIT_MERGE_MSG;
2033 item->commit = NULL;
2034 item->arg = bol;
2035 item->arg_len = (int)(eol - bol);
2036 return 0;
2040 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2041 saved = *end_of_object_name;
2042 *end_of_object_name = '\0';
2043 status = get_oid(bol, &commit_oid);
2044 *end_of_object_name = saved;
2046 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2047 item->arg_len = (int)(eol - item->arg);
2049 if (status < 0)
2050 return -1;
2052 item->commit = lookup_commit_reference(the_repository, &commit_oid);
2053 return !item->commit;
2056 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2058 struct todo_item *item;
2059 char *p = buf, *next_p;
2060 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2062 for (i = 1; *p; i++, p = next_p) {
2063 char *eol = strchrnul(p, '\n');
2065 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2067 if (p != eol && eol[-1] == '\r')
2068 eol--; /* strip Carriage Return */
2070 item = append_new_todo(todo_list);
2071 item->offset_in_buf = p - todo_list->buf.buf;
2072 if (parse_insn_line(item, p, eol)) {
2073 res = error(_("invalid line %d: %.*s"),
2074 i, (int)(eol - p), p);
2075 item->command = TODO_NOOP;
2078 if (fixup_okay)
2079 ; /* do nothing */
2080 else if (is_fixup(item->command))
2081 return error(_("cannot '%s' without a previous commit"),
2082 command_to_string(item->command));
2083 else if (!is_noop(item->command))
2084 fixup_okay = 1;
2087 return res;
2090 static int count_commands(struct todo_list *todo_list)
2092 int count = 0, i;
2094 for (i = 0; i < todo_list->nr; i++)
2095 if (todo_list->items[i].command != TODO_COMMENT)
2096 count++;
2098 return count;
2101 static int get_item_line_offset(struct todo_list *todo_list, int index)
2103 return index < todo_list->nr ?
2104 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2107 static const char *get_item_line(struct todo_list *todo_list, int index)
2109 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2112 static int get_item_line_length(struct todo_list *todo_list, int index)
2114 return get_item_line_offset(todo_list, index + 1)
2115 - get_item_line_offset(todo_list, index);
2118 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2120 int fd;
2121 ssize_t len;
2123 fd = open(path, O_RDONLY);
2124 if (fd < 0)
2125 return error_errno(_("could not open '%s'"), path);
2126 len = strbuf_read(sb, fd, 0);
2127 close(fd);
2128 if (len < 0)
2129 return error(_("could not read '%s'."), path);
2130 return len;
2133 static int read_populate_todo(struct todo_list *todo_list,
2134 struct replay_opts *opts)
2136 struct stat st;
2137 const char *todo_file = get_todo_path(opts);
2138 int res;
2140 strbuf_reset(&todo_list->buf);
2141 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2142 return -1;
2144 res = stat(todo_file, &st);
2145 if (res)
2146 return error(_("could not stat '%s'"), todo_file);
2147 fill_stat_data(&todo_list->stat, &st);
2149 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2150 if (res) {
2151 if (is_rebase_i(opts))
2152 return error(_("please fix this using "
2153 "'git rebase --edit-todo'."));
2154 return error(_("unusable instruction sheet: '%s'"), todo_file);
2157 if (!todo_list->nr &&
2158 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2159 return error(_("no commits parsed."));
2161 if (!is_rebase_i(opts)) {
2162 enum todo_command valid =
2163 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2164 int i;
2166 for (i = 0; i < todo_list->nr; i++)
2167 if (valid == todo_list->items[i].command)
2168 continue;
2169 else if (valid == TODO_PICK)
2170 return error(_("cannot cherry-pick during a revert."));
2171 else
2172 return error(_("cannot revert during a cherry-pick."));
2175 if (is_rebase_i(opts)) {
2176 struct todo_list done = TODO_LIST_INIT;
2177 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2179 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2180 !parse_insn_buffer(done.buf.buf, &done))
2181 todo_list->done_nr = count_commands(&done);
2182 else
2183 todo_list->done_nr = 0;
2185 todo_list->total_nr = todo_list->done_nr
2186 + count_commands(todo_list);
2187 todo_list_release(&done);
2189 if (f) {
2190 fprintf(f, "%d\n", todo_list->total_nr);
2191 fclose(f);
2195 return 0;
2198 static int git_config_string_dup(char **dest,
2199 const char *var, const char *value)
2201 if (!value)
2202 return config_error_nonbool(var);
2203 free(*dest);
2204 *dest = xstrdup(value);
2205 return 0;
2208 static int populate_opts_cb(const char *key, const char *value, void *data)
2210 struct replay_opts *opts = data;
2211 int error_flag = 1;
2213 if (!value)
2214 error_flag = 0;
2215 else if (!strcmp(key, "options.no-commit"))
2216 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2217 else if (!strcmp(key, "options.edit"))
2218 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2219 else if (!strcmp(key, "options.signoff"))
2220 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2221 else if (!strcmp(key, "options.record-origin"))
2222 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2223 else if (!strcmp(key, "options.allow-ff"))
2224 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2225 else if (!strcmp(key, "options.mainline"))
2226 opts->mainline = git_config_int(key, value);
2227 else if (!strcmp(key, "options.strategy"))
2228 git_config_string_dup(&opts->strategy, key, value);
2229 else if (!strcmp(key, "options.gpg-sign"))
2230 git_config_string_dup(&opts->gpg_sign, key, value);
2231 else if (!strcmp(key, "options.strategy-option")) {
2232 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2233 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2234 } else if (!strcmp(key, "options.allow-rerere-auto"))
2235 opts->allow_rerere_auto =
2236 git_config_bool_or_int(key, value, &error_flag) ?
2237 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2238 else
2239 return error(_("invalid key: %s"), key);
2241 if (!error_flag)
2242 return error(_("invalid value for %s: %s"), key, value);
2244 return 0;
2247 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2249 int i;
2250 char *strategy_opts_string;
2252 strbuf_reset(buf);
2253 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2254 return;
2255 opts->strategy = strbuf_detach(buf, NULL);
2256 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2257 return;
2259 strategy_opts_string = buf->buf;
2260 if (*strategy_opts_string == ' ')
2261 strategy_opts_string++;
2262 opts->xopts_nr = split_cmdline(strategy_opts_string,
2263 (const char ***)&opts->xopts);
2264 for (i = 0; i < opts->xopts_nr; i++) {
2265 const char *arg = opts->xopts[i];
2267 skip_prefix(arg, "--", &arg);
2268 opts->xopts[i] = xstrdup(arg);
2272 static int read_populate_opts(struct replay_opts *opts)
2274 if (is_rebase_i(opts)) {
2275 struct strbuf buf = STRBUF_INIT;
2277 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2278 if (!starts_with(buf.buf, "-S"))
2279 strbuf_reset(&buf);
2280 else {
2281 free(opts->gpg_sign);
2282 opts->gpg_sign = xstrdup(buf.buf + 2);
2284 strbuf_reset(&buf);
2287 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2288 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2289 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2290 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2291 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2292 strbuf_reset(&buf);
2295 if (file_exists(rebase_path_verbose()))
2296 opts->verbose = 1;
2298 if (file_exists(rebase_path_signoff())) {
2299 opts->allow_ff = 0;
2300 opts->signoff = 1;
2303 read_strategy_opts(opts, &buf);
2304 strbuf_release(&buf);
2306 if (read_oneliner(&opts->current_fixups,
2307 rebase_path_current_fixups(), 1)) {
2308 const char *p = opts->current_fixups.buf;
2309 opts->current_fixup_count = 1;
2310 while ((p = strchr(p, '\n'))) {
2311 opts->current_fixup_count++;
2312 p++;
2316 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2317 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2318 return error(_("unusable squash-onto"));
2319 opts->have_squash_onto = 1;
2322 return 0;
2325 if (!file_exists(git_path_opts_file()))
2326 return 0;
2328 * The function git_parse_source(), called from git_config_from_file(),
2329 * may die() in case of a syntactically incorrect file. We do not care
2330 * about this case, though, because we wrote that file ourselves, so we
2331 * are pretty certain that it is syntactically correct.
2333 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2334 return error(_("malformed options sheet: '%s'"),
2335 git_path_opts_file());
2336 return 0;
2339 static int walk_revs_populate_todo(struct todo_list *todo_list,
2340 struct replay_opts *opts)
2342 enum todo_command command = opts->action == REPLAY_PICK ?
2343 TODO_PICK : TODO_REVERT;
2344 const char *command_string = todo_command_info[command].str;
2345 struct commit *commit;
2347 if (prepare_revs(opts))
2348 return -1;
2350 while ((commit = get_revision(opts->revs))) {
2351 struct todo_item *item = append_new_todo(todo_list);
2352 const char *commit_buffer = get_commit_buffer(commit, NULL);
2353 const char *subject;
2354 int subject_len;
2356 item->command = command;
2357 item->commit = commit;
2358 item->arg = NULL;
2359 item->arg_len = 0;
2360 item->offset_in_buf = todo_list->buf.len;
2361 subject_len = find_commit_subject(commit_buffer, &subject);
2362 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2363 short_commit_name(commit), subject_len, subject);
2364 unuse_commit_buffer(commit, commit_buffer);
2367 if (!todo_list->nr)
2368 return error(_("empty commit set passed"));
2370 return 0;
2373 static int create_seq_dir(void)
2375 if (file_exists(git_path_seq_dir())) {
2376 error(_("a cherry-pick or revert is already in progress"));
2377 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2378 return -1;
2379 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2380 return error_errno(_("could not create sequencer directory '%s'"),
2381 git_path_seq_dir());
2382 return 0;
2385 static int save_head(const char *head)
2387 struct lock_file head_lock = LOCK_INIT;
2388 struct strbuf buf = STRBUF_INIT;
2389 int fd;
2390 ssize_t written;
2392 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2393 if (fd < 0)
2394 return error_errno(_("could not lock HEAD"));
2395 strbuf_addf(&buf, "%s\n", head);
2396 written = write_in_full(fd, buf.buf, buf.len);
2397 strbuf_release(&buf);
2398 if (written < 0) {
2399 error_errno(_("could not write to '%s'"), git_path_head_file());
2400 rollback_lock_file(&head_lock);
2401 return -1;
2403 if (commit_lock_file(&head_lock) < 0)
2404 return error(_("failed to finalize '%s'"), git_path_head_file());
2405 return 0;
2408 static int rollback_is_safe(void)
2410 struct strbuf sb = STRBUF_INIT;
2411 struct object_id expected_head, actual_head;
2413 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2414 strbuf_trim(&sb);
2415 if (get_oid_hex(sb.buf, &expected_head)) {
2416 strbuf_release(&sb);
2417 die(_("could not parse %s"), git_path_abort_safety_file());
2419 strbuf_release(&sb);
2421 else if (errno == ENOENT)
2422 oidclr(&expected_head);
2423 else
2424 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2426 if (get_oid("HEAD", &actual_head))
2427 oidclr(&actual_head);
2429 return oideq(&actual_head, &expected_head);
2432 static int reset_for_rollback(const struct object_id *oid)
2434 const char *argv[4]; /* reset --merge <arg> + NULL */
2436 argv[0] = "reset";
2437 argv[1] = "--merge";
2438 argv[2] = oid_to_hex(oid);
2439 argv[3] = NULL;
2440 return run_command_v_opt(argv, RUN_GIT_CMD);
2443 static int rollback_single_pick(void)
2445 struct object_id head_oid;
2447 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
2448 !file_exists(git_path_revert_head(the_repository)))
2449 return error(_("no cherry-pick or revert in progress"));
2450 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2451 return error(_("cannot resolve HEAD"));
2452 if (is_null_oid(&head_oid))
2453 return error(_("cannot abort from a branch yet to be born"));
2454 return reset_for_rollback(&head_oid);
2457 int sequencer_rollback(struct replay_opts *opts)
2459 FILE *f;
2460 struct object_id oid;
2461 struct strbuf buf = STRBUF_INIT;
2462 const char *p;
2464 f = fopen(git_path_head_file(), "r");
2465 if (!f && errno == ENOENT) {
2467 * There is no multiple-cherry-pick in progress.
2468 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2469 * a single-cherry-pick in progress, abort that.
2471 return rollback_single_pick();
2473 if (!f)
2474 return error_errno(_("cannot open '%s'"), git_path_head_file());
2475 if (strbuf_getline_lf(&buf, f)) {
2476 error(_("cannot read '%s': %s"), git_path_head_file(),
2477 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2478 fclose(f);
2479 goto fail;
2481 fclose(f);
2482 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2483 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2484 git_path_head_file());
2485 goto fail;
2487 if (is_null_oid(&oid)) {
2488 error(_("cannot abort from a branch yet to be born"));
2489 goto fail;
2492 if (!rollback_is_safe()) {
2493 /* Do not error, just do not rollback */
2494 warning(_("You seem to have moved HEAD. "
2495 "Not rewinding, check your HEAD!"));
2496 } else
2497 if (reset_for_rollback(&oid))
2498 goto fail;
2499 strbuf_release(&buf);
2500 return sequencer_remove_state(opts);
2501 fail:
2502 strbuf_release(&buf);
2503 return -1;
2506 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2508 struct lock_file todo_lock = LOCK_INIT;
2509 const char *todo_path = get_todo_path(opts);
2510 int next = todo_list->current, offset, fd;
2513 * rebase -i writes "git-rebase-todo" without the currently executing
2514 * command, appending it to "done" instead.
2516 if (is_rebase_i(opts))
2517 next++;
2519 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2520 if (fd < 0)
2521 return error_errno(_("could not lock '%s'"), todo_path);
2522 offset = get_item_line_offset(todo_list, next);
2523 if (write_in_full(fd, todo_list->buf.buf + offset,
2524 todo_list->buf.len - offset) < 0)
2525 return error_errno(_("could not write to '%s'"), todo_path);
2526 if (commit_lock_file(&todo_lock) < 0)
2527 return error(_("failed to finalize '%s'"), todo_path);
2529 if (is_rebase_i(opts) && next > 0) {
2530 const char *done = rebase_path_done();
2531 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2532 int ret = 0;
2534 if (fd < 0)
2535 return 0;
2536 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2537 get_item_line_length(todo_list, next - 1))
2538 < 0)
2539 ret = error_errno(_("could not write to '%s'"), done);
2540 if (close(fd) < 0)
2541 ret = error_errno(_("failed to finalize '%s'"), done);
2542 return ret;
2544 return 0;
2547 static int save_opts(struct replay_opts *opts)
2549 const char *opts_file = git_path_opts_file();
2550 int res = 0;
2552 if (opts->no_commit)
2553 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2554 if (opts->edit)
2555 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2556 if (opts->signoff)
2557 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2558 if (opts->record_origin)
2559 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2560 if (opts->allow_ff)
2561 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2562 if (opts->mainline) {
2563 struct strbuf buf = STRBUF_INIT;
2564 strbuf_addf(&buf, "%d", opts->mainline);
2565 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2566 strbuf_release(&buf);
2568 if (opts->strategy)
2569 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2570 if (opts->gpg_sign)
2571 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2572 if (opts->xopts) {
2573 int i;
2574 for (i = 0; i < opts->xopts_nr; i++)
2575 res |= git_config_set_multivar_in_file_gently(opts_file,
2576 "options.strategy-option",
2577 opts->xopts[i], "^$", 0);
2579 if (opts->allow_rerere_auto)
2580 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2581 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2582 "true" : "false");
2583 return res;
2586 static int make_patch(struct commit *commit, struct replay_opts *opts)
2588 struct strbuf buf = STRBUF_INIT;
2589 struct rev_info log_tree_opt;
2590 const char *subject, *p;
2591 int res = 0;
2593 p = short_commit_name(commit);
2594 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2595 return -1;
2596 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2597 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2598 res |= error(_("could not update %s"), "REBASE_HEAD");
2600 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2601 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2602 init_revisions(&log_tree_opt, NULL);
2603 log_tree_opt.abbrev = 0;
2604 log_tree_opt.diff = 1;
2605 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2606 log_tree_opt.disable_stdin = 1;
2607 log_tree_opt.no_commit_id = 1;
2608 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2609 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2610 if (!log_tree_opt.diffopt.file)
2611 res |= error_errno(_("could not open '%s'"), buf.buf);
2612 else {
2613 res |= log_tree_commit(&log_tree_opt, commit);
2614 fclose(log_tree_opt.diffopt.file);
2616 strbuf_reset(&buf);
2618 strbuf_addf(&buf, "%s/message", get_dir(opts));
2619 if (!file_exists(buf.buf)) {
2620 const char *commit_buffer = get_commit_buffer(commit, NULL);
2621 find_commit_subject(commit_buffer, &subject);
2622 res |= write_message(subject, strlen(subject), buf.buf, 1);
2623 unuse_commit_buffer(commit, commit_buffer);
2625 strbuf_release(&buf);
2627 return res;
2630 static int intend_to_amend(void)
2632 struct object_id head;
2633 char *p;
2635 if (get_oid("HEAD", &head))
2636 return error(_("cannot read HEAD"));
2638 p = oid_to_hex(&head);
2639 return write_message(p, strlen(p), rebase_path_amend(), 1);
2642 static int error_with_patch(struct commit *commit,
2643 const char *subject, int subject_len,
2644 struct replay_opts *opts, int exit_code, int to_amend)
2646 if (commit) {
2647 if (make_patch(commit, opts))
2648 return -1;
2649 } else if (copy_file(rebase_path_message(),
2650 git_path_merge_msg(the_repository), 0666))
2651 return error(_("unable to copy '%s' to '%s'"),
2652 git_path_merge_msg(the_repository), rebase_path_message());
2654 if (to_amend) {
2655 if (intend_to_amend())
2656 return -1;
2658 fprintf(stderr,
2659 _("You can amend the commit now, with\n"
2660 "\n"
2661 " git commit --amend %s\n"
2662 "\n"
2663 "Once you are satisfied with your changes, run\n"
2664 "\n"
2665 " git rebase --continue\n"),
2666 gpg_sign_opt_quoted(opts));
2667 } else if (exit_code) {
2668 if (commit)
2669 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2670 short_commit_name(commit), subject_len, subject);
2671 else
2673 * We don't have the hash of the parent so
2674 * just print the line from the todo file.
2676 fprintf_ln(stderr, _("Could not merge %.*s"),
2677 subject_len, subject);
2680 return exit_code;
2683 static int error_failed_squash(struct commit *commit,
2684 struct replay_opts *opts, int subject_len, const char *subject)
2686 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2687 return error(_("could not copy '%s' to '%s'"),
2688 rebase_path_squash_msg(), rebase_path_message());
2689 unlink(git_path_merge_msg(the_repository));
2690 if (copy_file(git_path_merge_msg(the_repository), rebase_path_message(), 0666))
2691 return error(_("could not copy '%s' to '%s'"),
2692 rebase_path_message(),
2693 git_path_merge_msg(the_repository));
2694 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2697 static int do_exec(const char *command_line)
2699 struct argv_array child_env = ARGV_ARRAY_INIT;
2700 const char *child_argv[] = { NULL, NULL };
2701 int dirty, status;
2703 fprintf(stderr, "Executing: %s\n", command_line);
2704 child_argv[0] = command_line;
2705 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2706 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2707 absolute_path(get_git_work_tree()));
2708 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2709 child_env.argv);
2711 /* force re-reading of the cache */
2712 if (discard_cache() < 0 || read_cache() < 0)
2713 return error(_("could not read index"));
2715 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2717 if (status) {
2718 warning(_("execution failed: %s\n%s"
2719 "You can fix the problem, and then run\n"
2720 "\n"
2721 " git rebase --continue\n"
2722 "\n"),
2723 command_line,
2724 dirty ? N_("and made changes to the index and/or the "
2725 "working tree\n") : "");
2726 if (status == 127)
2727 /* command not found */
2728 status = 1;
2729 } else if (dirty) {
2730 warning(_("execution succeeded: %s\nbut "
2731 "left changes to the index and/or the working tree\n"
2732 "Commit or stash your changes, and then run\n"
2733 "\n"
2734 " git rebase --continue\n"
2735 "\n"), command_line);
2736 status = 1;
2739 argv_array_clear(&child_env);
2741 return status;
2744 static int safe_append(const char *filename, const char *fmt, ...)
2746 va_list ap;
2747 struct lock_file lock = LOCK_INIT;
2748 int fd = hold_lock_file_for_update(&lock, filename,
2749 LOCK_REPORT_ON_ERROR);
2750 struct strbuf buf = STRBUF_INIT;
2752 if (fd < 0)
2753 return -1;
2755 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2756 error_errno(_("could not read '%s'"), filename);
2757 rollback_lock_file(&lock);
2758 return -1;
2760 strbuf_complete(&buf, '\n');
2761 va_start(ap, fmt);
2762 strbuf_vaddf(&buf, fmt, ap);
2763 va_end(ap);
2765 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2766 error_errno(_("could not write to '%s'"), filename);
2767 strbuf_release(&buf);
2768 rollback_lock_file(&lock);
2769 return -1;
2771 if (commit_lock_file(&lock) < 0) {
2772 strbuf_release(&buf);
2773 rollback_lock_file(&lock);
2774 return error(_("failed to finalize '%s'"), filename);
2777 strbuf_release(&buf);
2778 return 0;
2781 static int do_label(const char *name, int len)
2783 struct ref_store *refs = get_main_ref_store(the_repository);
2784 struct ref_transaction *transaction;
2785 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2786 struct strbuf msg = STRBUF_INIT;
2787 int ret = 0;
2788 struct object_id head_oid;
2790 if (len == 1 && *name == '#')
2791 return error(_("illegal label name: '%.*s'"), len, name);
2793 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2794 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2796 transaction = ref_store_transaction_begin(refs, &err);
2797 if (!transaction) {
2798 error("%s", err.buf);
2799 ret = -1;
2800 } else if (get_oid("HEAD", &head_oid)) {
2801 error(_("could not read HEAD"));
2802 ret = -1;
2803 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2804 NULL, 0, msg.buf, &err) < 0 ||
2805 ref_transaction_commit(transaction, &err)) {
2806 error("%s", err.buf);
2807 ret = -1;
2809 ref_transaction_free(transaction);
2810 strbuf_release(&err);
2811 strbuf_release(&msg);
2813 if (!ret)
2814 ret = safe_append(rebase_path_refs_to_delete(),
2815 "%s\n", ref_name.buf);
2816 strbuf_release(&ref_name);
2818 return ret;
2821 static const char *reflog_message(struct replay_opts *opts,
2822 const char *sub_action, const char *fmt, ...);
2824 static int do_reset(const char *name, int len, struct replay_opts *opts)
2826 struct strbuf ref_name = STRBUF_INIT;
2827 struct object_id oid;
2828 struct lock_file lock = LOCK_INIT;
2829 struct tree_desc desc;
2830 struct tree *tree;
2831 struct unpack_trees_options unpack_tree_opts;
2832 int ret = 0, i;
2834 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2835 return -1;
2837 if (len == 10 && !strncmp("[new root]", name, len)) {
2838 if (!opts->have_squash_onto) {
2839 const char *hex;
2840 if (commit_tree("", 0, the_hash_algo->empty_tree,
2841 NULL, &opts->squash_onto,
2842 NULL, NULL))
2843 return error(_("writing fake root commit"));
2844 opts->have_squash_onto = 1;
2845 hex = oid_to_hex(&opts->squash_onto);
2846 if (write_message(hex, strlen(hex),
2847 rebase_path_squash_onto(), 0))
2848 return error(_("writing squash-onto"));
2850 oidcpy(&oid, &opts->squash_onto);
2851 } else {
2852 /* Determine the length of the label */
2853 for (i = 0; i < len; i++)
2854 if (isspace(name[i]))
2855 len = i;
2857 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2858 if (get_oid(ref_name.buf, &oid) &&
2859 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2860 error(_("could not read '%s'"), ref_name.buf);
2861 rollback_lock_file(&lock);
2862 strbuf_release(&ref_name);
2863 return -1;
2867 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2868 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2869 unpack_tree_opts.head_idx = 1;
2870 unpack_tree_opts.src_index = &the_index;
2871 unpack_tree_opts.dst_index = &the_index;
2872 unpack_tree_opts.fn = oneway_merge;
2873 unpack_tree_opts.merge = 1;
2874 unpack_tree_opts.update = 1;
2876 if (read_cache_unmerged()) {
2877 rollback_lock_file(&lock);
2878 strbuf_release(&ref_name);
2879 return error_resolve_conflict(_(action_name(opts)));
2882 if (!fill_tree_descriptor(&desc, &oid)) {
2883 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2884 rollback_lock_file(&lock);
2885 free((void *)desc.buffer);
2886 strbuf_release(&ref_name);
2887 return -1;
2890 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2891 rollback_lock_file(&lock);
2892 free((void *)desc.buffer);
2893 strbuf_release(&ref_name);
2894 return -1;
2897 tree = parse_tree_indirect(&oid);
2898 prime_cache_tree(&the_index, tree);
2900 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2901 ret = error(_("could not write index"));
2902 free((void *)desc.buffer);
2904 if (!ret)
2905 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2906 len, name), "HEAD", &oid,
2907 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2909 strbuf_release(&ref_name);
2910 return ret;
2913 static struct commit *lookup_label(const char *label, int len,
2914 struct strbuf *buf)
2916 struct commit *commit;
2918 strbuf_reset(buf);
2919 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
2920 commit = lookup_commit_reference_by_name(buf->buf);
2921 if (!commit) {
2922 /* fall back to non-rewritten ref or commit */
2923 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
2924 commit = lookup_commit_reference_by_name(buf->buf);
2927 if (!commit)
2928 error(_("could not resolve '%s'"), buf->buf);
2930 return commit;
2933 static int do_merge(struct commit *commit, const char *arg, int arg_len,
2934 int flags, struct replay_opts *opts)
2936 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2937 EDIT_MSG | VERIFY_MSG : 0;
2938 struct strbuf ref_name = STRBUF_INIT;
2939 struct commit *head_commit, *merge_commit, *i;
2940 struct commit_list *bases, *j, *reversed = NULL;
2941 struct commit_list *to_merge = NULL, **tail = &to_merge;
2942 struct merge_options o;
2943 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
2944 static struct lock_file lock;
2945 const char *p;
2947 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2948 ret = -1;
2949 goto leave_merge;
2952 head_commit = lookup_commit_reference_by_name("HEAD");
2953 if (!head_commit) {
2954 ret = error(_("cannot merge without a current revision"));
2955 goto leave_merge;
2959 * For octopus merges, the arg starts with the list of revisions to be
2960 * merged. The list is optionally followed by '#' and the oneline.
2962 merge_arg_len = oneline_offset = arg_len;
2963 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
2964 if (!*p)
2965 break;
2966 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2967 p += 1 + strspn(p + 1, " \t\n");
2968 oneline_offset = p - arg;
2969 break;
2971 k = strcspn(p, " \t\n");
2972 if (!k)
2973 continue;
2974 merge_commit = lookup_label(p, k, &ref_name);
2975 if (!merge_commit) {
2976 ret = error(_("unable to parse '%.*s'"), k, p);
2977 goto leave_merge;
2979 tail = &commit_list_insert(merge_commit, tail)->next;
2980 p += k;
2981 merge_arg_len = p - arg;
2984 if (!to_merge) {
2985 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
2986 goto leave_merge;
2989 if (opts->have_squash_onto &&
2990 oideq(&head_commit->object.oid, &opts->squash_onto)) {
2992 * When the user tells us to "merge" something into a
2993 * "[new root]", let's simply fast-forward to the merge head.
2995 rollback_lock_file(&lock);
2996 if (to_merge->next)
2997 ret = error(_("octopus merge cannot be executed on "
2998 "top of a [new root]"));
2999 else
3000 ret = fast_forward_to(&to_merge->item->object.oid,
3001 &head_commit->object.oid, 0,
3002 opts);
3003 goto leave_merge;
3006 if (commit) {
3007 const char *message = get_commit_buffer(commit, NULL);
3008 const char *body;
3009 int len;
3011 if (!message) {
3012 ret = error(_("could not get commit message of '%s'"),
3013 oid_to_hex(&commit->object.oid));
3014 goto leave_merge;
3016 write_author_script(message);
3017 find_commit_subject(message, &body);
3018 len = strlen(body);
3019 ret = write_message(body, len, git_path_merge_msg(the_repository), 0);
3020 unuse_commit_buffer(commit, message);
3021 if (ret) {
3022 error_errno(_("could not write '%s'"),
3023 git_path_merge_msg(the_repository));
3024 goto leave_merge;
3026 } else {
3027 struct strbuf buf = STRBUF_INIT;
3028 int len;
3030 strbuf_addf(&buf, "author %s", git_author_info(0));
3031 write_author_script(buf.buf);
3032 strbuf_reset(&buf);
3034 if (oneline_offset < arg_len) {
3035 p = arg + oneline_offset;
3036 len = arg_len - oneline_offset;
3037 } else {
3038 strbuf_addf(&buf, "Merge %s '%.*s'",
3039 to_merge->next ? "branches" : "branch",
3040 merge_arg_len, arg);
3041 p = buf.buf;
3042 len = buf.len;
3045 ret = write_message(p, len, git_path_merge_msg(the_repository), 0);
3046 strbuf_release(&buf);
3047 if (ret) {
3048 error_errno(_("could not write '%s'"),
3049 git_path_merge_msg(the_repository));
3050 goto leave_merge;
3055 * If HEAD is not identical to the first parent of the original merge
3056 * commit, we cannot fast-forward.
3058 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3059 oideq(&commit->parents->item->object.oid,
3060 &head_commit->object.oid);
3063 * If any merge head is different from the original one, we cannot
3064 * fast-forward.
3066 if (can_fast_forward) {
3067 struct commit_list *p = commit->parents->next;
3069 for (j = to_merge; j && p; j = j->next, p = p->next)
3070 if (!oideq(&j->item->object.oid,
3071 &p->item->object.oid)) {
3072 can_fast_forward = 0;
3073 break;
3076 * If the number of merge heads differs from the original merge
3077 * commit, we cannot fast-forward.
3079 if (j || p)
3080 can_fast_forward = 0;
3083 if (can_fast_forward) {
3084 rollback_lock_file(&lock);
3085 ret = fast_forward_to(&commit->object.oid,
3086 &head_commit->object.oid, 0, opts);
3087 goto leave_merge;
3090 if (to_merge->next) {
3091 /* Octopus merge */
3092 struct child_process cmd = CHILD_PROCESS_INIT;
3094 if (read_env_script(&cmd.env_array)) {
3095 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3097 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3098 goto leave_merge;
3101 cmd.git_cmd = 1;
3102 argv_array_push(&cmd.args, "merge");
3103 argv_array_push(&cmd.args, "-s");
3104 argv_array_push(&cmd.args, "octopus");
3105 argv_array_push(&cmd.args, "--no-edit");
3106 argv_array_push(&cmd.args, "--no-ff");
3107 argv_array_push(&cmd.args, "--no-log");
3108 argv_array_push(&cmd.args, "--no-stat");
3109 argv_array_push(&cmd.args, "-F");
3110 argv_array_push(&cmd.args, git_path_merge_msg(the_repository));
3111 if (opts->gpg_sign)
3112 argv_array_push(&cmd.args, opts->gpg_sign);
3114 /* Add the tips to be merged */
3115 for (j = to_merge; j; j = j->next)
3116 argv_array_push(&cmd.args,
3117 oid_to_hex(&j->item->object.oid));
3119 strbuf_release(&ref_name);
3120 unlink(git_path_cherry_pick_head(the_repository));
3121 rollback_lock_file(&lock);
3123 rollback_lock_file(&lock);
3124 ret = run_command(&cmd);
3126 /* force re-reading of the cache */
3127 if (!ret && (discard_cache() < 0 || read_cache() < 0))
3128 ret = error(_("could not read index"));
3129 goto leave_merge;
3132 merge_commit = to_merge->item;
3133 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3134 git_path_merge_head(the_repository), 0);
3135 write_message("no-ff", 5, git_path_merge_mode(the_repository), 0);
3137 bases = get_merge_bases(head_commit, merge_commit);
3138 if (bases && oideq(&merge_commit->object.oid,
3139 &bases->item->object.oid)) {
3140 ret = 0;
3141 /* skip merging an ancestor of HEAD */
3142 goto leave_merge;
3145 for (j = bases; j; j = j->next)
3146 commit_list_insert(j->item, &reversed);
3147 free_commit_list(bases);
3149 read_cache();
3150 init_merge_options(&o);
3151 o.branch1 = "HEAD";
3152 o.branch2 = ref_name.buf;
3153 o.buffer_output = 2;
3155 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3156 if (ret <= 0)
3157 fputs(o.obuf.buf, stdout);
3158 strbuf_release(&o.obuf);
3159 if (ret < 0) {
3160 error(_("could not even attempt to merge '%.*s'"),
3161 merge_arg_len, arg);
3162 goto leave_merge;
3165 * The return value of merge_recursive() is 1 on clean, and 0 on
3166 * unclean merge.
3168 * Let's reverse that, so that do_merge() returns 0 upon success and
3169 * 1 upon failed merge (keeping the return value -1 for the cases where
3170 * we will want to reschedule the `merge` command).
3172 ret = !ret;
3174 if (active_cache_changed &&
3175 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3176 ret = error(_("merge: Unable to write new index file"));
3177 goto leave_merge;
3180 rollback_lock_file(&lock);
3181 if (ret)
3182 rerere(opts->allow_rerere_auto);
3183 else
3185 * In case of problems, we now want to return a positive
3186 * value (a negative one would indicate that the `merge`
3187 * command needs to be rescheduled).
3189 ret = !!run_git_commit(git_path_merge_msg(the_repository), opts,
3190 run_commit_flags);
3192 leave_merge:
3193 strbuf_release(&ref_name);
3194 rollback_lock_file(&lock);
3195 free_commit_list(to_merge);
3196 return ret;
3199 static int is_final_fixup(struct todo_list *todo_list)
3201 int i = todo_list->current;
3203 if (!is_fixup(todo_list->items[i].command))
3204 return 0;
3206 while (++i < todo_list->nr)
3207 if (is_fixup(todo_list->items[i].command))
3208 return 0;
3209 else if (!is_noop(todo_list->items[i].command))
3210 break;
3211 return 1;
3214 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3216 int i;
3218 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3219 if (!is_noop(todo_list->items[i].command))
3220 return todo_list->items[i].command;
3222 return -1;
3225 static int apply_autostash(struct replay_opts *opts)
3227 struct strbuf stash_sha1 = STRBUF_INIT;
3228 struct child_process child = CHILD_PROCESS_INIT;
3229 int ret = 0;
3231 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3232 strbuf_release(&stash_sha1);
3233 return 0;
3235 strbuf_trim(&stash_sha1);
3237 child.git_cmd = 1;
3238 child.no_stdout = 1;
3239 child.no_stderr = 1;
3240 argv_array_push(&child.args, "stash");
3241 argv_array_push(&child.args, "apply");
3242 argv_array_push(&child.args, stash_sha1.buf);
3243 if (!run_command(&child))
3244 fprintf(stderr, _("Applied autostash.\n"));
3245 else {
3246 struct child_process store = CHILD_PROCESS_INIT;
3248 store.git_cmd = 1;
3249 argv_array_push(&store.args, "stash");
3250 argv_array_push(&store.args, "store");
3251 argv_array_push(&store.args, "-m");
3252 argv_array_push(&store.args, "autostash");
3253 argv_array_push(&store.args, "-q");
3254 argv_array_push(&store.args, stash_sha1.buf);
3255 if (run_command(&store))
3256 ret = error(_("cannot store %s"), stash_sha1.buf);
3257 else
3258 fprintf(stderr,
3259 _("Applying autostash resulted in conflicts.\n"
3260 "Your changes are safe in the stash.\n"
3261 "You can run \"git stash pop\" or"
3262 " \"git stash drop\" at any time.\n"));
3265 strbuf_release(&stash_sha1);
3266 return ret;
3269 static const char *reflog_message(struct replay_opts *opts,
3270 const char *sub_action, const char *fmt, ...)
3272 va_list ap;
3273 static struct strbuf buf = STRBUF_INIT;
3275 va_start(ap, fmt);
3276 strbuf_reset(&buf);
3277 strbuf_addstr(&buf, action_name(opts));
3278 if (sub_action)
3279 strbuf_addf(&buf, " (%s)", sub_action);
3280 if (fmt) {
3281 strbuf_addstr(&buf, ": ");
3282 strbuf_vaddf(&buf, fmt, ap);
3284 va_end(ap);
3286 return buf.buf;
3289 static const char rescheduled_advice[] =
3290 N_("Could not execute the todo command\n"
3291 "\n"
3292 " %.*s"
3293 "\n"
3294 "It has been rescheduled; To edit the command before continuing, please\n"
3295 "edit the todo list first:\n"
3296 "\n"
3297 " git rebase --edit-todo\n"
3298 " git rebase --continue\n");
3300 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3302 int res = 0, reschedule = 0;
3304 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3305 if (opts->allow_ff)
3306 assert(!(opts->signoff || opts->no_commit ||
3307 opts->record_origin || opts->edit));
3308 if (read_and_refresh_cache(opts))
3309 return -1;
3311 while (todo_list->current < todo_list->nr) {
3312 struct todo_item *item = todo_list->items + todo_list->current;
3313 if (save_todo(todo_list, opts))
3314 return -1;
3315 if (is_rebase_i(opts)) {
3316 if (item->command != TODO_COMMENT) {
3317 FILE *f = fopen(rebase_path_msgnum(), "w");
3319 todo_list->done_nr++;
3321 if (f) {
3322 fprintf(f, "%d\n", todo_list->done_nr);
3323 fclose(f);
3325 fprintf(stderr, "Rebasing (%d/%d)%s",
3326 todo_list->done_nr,
3327 todo_list->total_nr,
3328 opts->verbose ? "\n" : "\r");
3330 unlink(rebase_path_message());
3331 unlink(rebase_path_author_script());
3332 unlink(rebase_path_stopped_sha());
3333 unlink(rebase_path_amend());
3334 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3336 if (item->command <= TODO_SQUASH) {
3337 if (is_rebase_i(opts))
3338 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3339 command_to_string(item->command), NULL),
3341 res = do_pick_commit(item->command, item->commit,
3342 opts, is_final_fixup(todo_list));
3343 if (is_rebase_i(opts) && res < 0) {
3344 /* Reschedule */
3345 advise(_(rescheduled_advice),
3346 get_item_line_length(todo_list,
3347 todo_list->current),
3348 get_item_line(todo_list,
3349 todo_list->current));
3350 todo_list->current--;
3351 if (save_todo(todo_list, opts))
3352 return -1;
3354 if (item->command == TODO_EDIT) {
3355 struct commit *commit = item->commit;
3356 if (!res)
3357 fprintf(stderr,
3358 _("Stopped at %s... %.*s\n"),
3359 short_commit_name(commit),
3360 item->arg_len, item->arg);
3361 return error_with_patch(commit,
3362 item->arg, item->arg_len, opts, res,
3363 !res);
3365 if (is_rebase_i(opts) && !res)
3366 record_in_rewritten(&item->commit->object.oid,
3367 peek_command(todo_list, 1));
3368 if (res && is_fixup(item->command)) {
3369 if (res == 1)
3370 intend_to_amend();
3371 return error_failed_squash(item->commit, opts,
3372 item->arg_len, item->arg);
3373 } else if (res && is_rebase_i(opts) && item->commit) {
3374 int to_amend = 0;
3375 struct object_id oid;
3378 * If we are rewording and have either
3379 * fast-forwarded already, or are about to
3380 * create a new root commit, we want to amend,
3381 * otherwise we do not.
3383 if (item->command == TODO_REWORD &&
3384 !get_oid("HEAD", &oid) &&
3385 (oideq(&item->commit->object.oid, &oid) ||
3386 (opts->have_squash_onto &&
3387 oideq(&opts->squash_onto, &oid))))
3388 to_amend = 1;
3390 return res | error_with_patch(item->commit,
3391 item->arg, item->arg_len, opts,
3392 res, to_amend);
3394 } else if (item->command == TODO_EXEC) {
3395 char *end_of_arg = (char *)(item->arg + item->arg_len);
3396 int saved = *end_of_arg;
3397 struct stat st;
3399 *end_of_arg = '\0';
3400 res = do_exec(item->arg);
3401 *end_of_arg = saved;
3403 /* Reread the todo file if it has changed. */
3404 if (res)
3405 ; /* fall through */
3406 else if (stat(get_todo_path(opts), &st))
3407 res = error_errno(_("could not stat '%s'"),
3408 get_todo_path(opts));
3409 else if (match_stat_data(&todo_list->stat, &st)) {
3410 todo_list_release(todo_list);
3411 if (read_populate_todo(todo_list, opts))
3412 res = -1; /* message was printed */
3413 /* `current` will be incremented below */
3414 todo_list->current = -1;
3416 } else if (item->command == TODO_LABEL) {
3417 if ((res = do_label(item->arg, item->arg_len)))
3418 reschedule = 1;
3419 } else if (item->command == TODO_RESET) {
3420 if ((res = do_reset(item->arg, item->arg_len, opts)))
3421 reschedule = 1;
3422 } else if (item->command == TODO_MERGE) {
3423 if ((res = do_merge(item->commit,
3424 item->arg, item->arg_len,
3425 item->flags, opts)) < 0)
3426 reschedule = 1;
3427 else if (item->commit)
3428 record_in_rewritten(&item->commit->object.oid,
3429 peek_command(todo_list, 1));
3430 if (res > 0)
3431 /* failed with merge conflicts */
3432 return error_with_patch(item->commit,
3433 item->arg,
3434 item->arg_len, opts,
3435 res, 0);
3436 } else if (!is_noop(item->command))
3437 return error(_("unknown command %d"), item->command);
3439 if (reschedule) {
3440 advise(_(rescheduled_advice),
3441 get_item_line_length(todo_list,
3442 todo_list->current),
3443 get_item_line(todo_list, todo_list->current));
3444 todo_list->current--;
3445 if (save_todo(todo_list, opts))
3446 return -1;
3447 if (item->commit)
3448 return error_with_patch(item->commit,
3449 item->arg,
3450 item->arg_len, opts,
3451 res, 0);
3454 todo_list->current++;
3455 if (res)
3456 return res;
3459 if (is_rebase_i(opts)) {
3460 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3461 struct stat st;
3463 /* Stopped in the middle, as planned? */
3464 if (todo_list->current < todo_list->nr)
3465 return 0;
3467 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3468 starts_with(head_ref.buf, "refs/")) {
3469 const char *msg;
3470 struct object_id head, orig;
3471 int res;
3473 if (get_oid("HEAD", &head)) {
3474 res = error(_("cannot read HEAD"));
3475 cleanup_head_ref:
3476 strbuf_release(&head_ref);
3477 strbuf_release(&buf);
3478 return res;
3480 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3481 get_oid_hex(buf.buf, &orig)) {
3482 res = error(_("could not read orig-head"));
3483 goto cleanup_head_ref;
3485 strbuf_reset(&buf);
3486 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3487 res = error(_("could not read 'onto'"));
3488 goto cleanup_head_ref;
3490 msg = reflog_message(opts, "finish", "%s onto %s",
3491 head_ref.buf, buf.buf);
3492 if (update_ref(msg, head_ref.buf, &head, &orig,
3493 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3494 res = error(_("could not update %s"),
3495 head_ref.buf);
3496 goto cleanup_head_ref;
3498 msg = reflog_message(opts, "finish", "returning to %s",
3499 head_ref.buf);
3500 if (create_symref("HEAD", head_ref.buf, msg)) {
3501 res = error(_("could not update HEAD to %s"),
3502 head_ref.buf);
3503 goto cleanup_head_ref;
3505 strbuf_reset(&buf);
3508 if (opts->verbose) {
3509 struct rev_info log_tree_opt;
3510 struct object_id orig, head;
3512 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3513 init_revisions(&log_tree_opt, NULL);
3514 log_tree_opt.diff = 1;
3515 log_tree_opt.diffopt.output_format =
3516 DIFF_FORMAT_DIFFSTAT;
3517 log_tree_opt.disable_stdin = 1;
3519 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3520 !get_oid(buf.buf, &orig) &&
3521 !get_oid("HEAD", &head)) {
3522 diff_tree_oid(&orig, &head, "",
3523 &log_tree_opt.diffopt);
3524 log_tree_diff_flush(&log_tree_opt);
3527 flush_rewritten_pending();
3528 if (!stat(rebase_path_rewritten_list(), &st) &&
3529 st.st_size > 0) {
3530 struct child_process child = CHILD_PROCESS_INIT;
3531 const char *post_rewrite_hook =
3532 find_hook("post-rewrite");
3534 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3535 child.git_cmd = 1;
3536 argv_array_push(&child.args, "notes");
3537 argv_array_push(&child.args, "copy");
3538 argv_array_push(&child.args, "--for-rewrite=rebase");
3539 /* we don't care if this copying failed */
3540 run_command(&child);
3542 if (post_rewrite_hook) {
3543 struct child_process hook = CHILD_PROCESS_INIT;
3545 hook.in = open(rebase_path_rewritten_list(),
3546 O_RDONLY);
3547 hook.stdout_to_stderr = 1;
3548 argv_array_push(&hook.args, post_rewrite_hook);
3549 argv_array_push(&hook.args, "rebase");
3550 /* we don't care if this hook failed */
3551 run_command(&hook);
3554 apply_autostash(opts);
3556 fprintf(stderr, "Successfully rebased and updated %s.\n",
3557 head_ref.buf);
3559 strbuf_release(&buf);
3560 strbuf_release(&head_ref);
3564 * Sequence of picks finished successfully; cleanup by
3565 * removing the .git/sequencer directory
3567 return sequencer_remove_state(opts);
3570 static int continue_single_pick(void)
3572 const char *argv[] = { "commit", NULL };
3574 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
3575 !file_exists(git_path_revert_head(the_repository)))
3576 return error(_("no cherry-pick or revert in progress"));
3577 return run_command_v_opt(argv, RUN_GIT_CMD);
3580 static int commit_staged_changes(struct replay_opts *opts,
3581 struct todo_list *todo_list)
3583 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3584 unsigned int final_fixup = 0, is_clean;
3586 if (has_unstaged_changes(1))
3587 return error(_("cannot rebase: You have unstaged changes."));
3589 is_clean = !has_uncommitted_changes(0);
3591 if (file_exists(rebase_path_amend())) {
3592 struct strbuf rev = STRBUF_INIT;
3593 struct object_id head, to_amend;
3595 if (get_oid("HEAD", &head))
3596 return error(_("cannot amend non-existing commit"));
3597 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3598 return error(_("invalid file: '%s'"), rebase_path_amend());
3599 if (get_oid_hex(rev.buf, &to_amend))
3600 return error(_("invalid contents: '%s'"),
3601 rebase_path_amend());
3602 if (!is_clean && !oideq(&head, &to_amend))
3603 return error(_("\nYou have uncommitted changes in your "
3604 "working tree. Please, commit them\n"
3605 "first and then run 'git rebase "
3606 "--continue' again."));
3608 * When skipping a failed fixup/squash, we need to edit the
3609 * commit message, the current fixup list and count, and if it
3610 * was the last fixup/squash in the chain, we need to clean up
3611 * the commit message and if there was a squash, let the user
3612 * edit it.
3614 if (is_clean && oideq(&head, &to_amend) &&
3615 opts->current_fixup_count > 0 &&
3616 file_exists(rebase_path_stopped_sha())) {
3617 const char *p = opts->current_fixups.buf;
3618 int len = opts->current_fixups.len;
3620 opts->current_fixup_count--;
3621 if (!len)
3622 BUG("Incorrect current_fixups:\n%s", p);
3623 while (len && p[len - 1] != '\n')
3624 len--;
3625 strbuf_setlen(&opts->current_fixups, len);
3626 if (write_message(p, len, rebase_path_current_fixups(),
3627 0) < 0)
3628 return error(_("could not write file: '%s'"),
3629 rebase_path_current_fixups());
3632 * If a fixup/squash in a fixup/squash chain failed, the
3633 * commit message is already correct, no need to commit
3634 * it again.
3636 * Only if it is the final command in the fixup/squash
3637 * chain, and only if the chain is longer than a single
3638 * fixup/squash command (which was just skipped), do we
3639 * actually need to re-commit with a cleaned up commit
3640 * message.
3642 if (opts->current_fixup_count > 0 &&
3643 !is_fixup(peek_command(todo_list, 0))) {
3644 final_fixup = 1;
3646 * If there was not a single "squash" in the
3647 * chain, we only need to clean up the commit
3648 * message, no need to bother the user with
3649 * opening the commit message in the editor.
3651 if (!starts_with(p, "squash ") &&
3652 !strstr(p, "\nsquash "))
3653 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3654 } else if (is_fixup(peek_command(todo_list, 0))) {
3656 * We need to update the squash message to skip
3657 * the latest commit message.
3659 struct commit *commit;
3660 const char *path = rebase_path_squash_msg();
3662 if (parse_head(&commit) ||
3663 !(p = get_commit_buffer(commit, NULL)) ||
3664 write_message(p, strlen(p), path, 0)) {
3665 unuse_commit_buffer(commit, p);
3666 return error(_("could not write file: "
3667 "'%s'"), path);
3669 unuse_commit_buffer(commit, p);
3673 strbuf_release(&rev);
3674 flags |= AMEND_MSG;
3677 if (is_clean) {
3678 const char *cherry_pick_head = git_path_cherry_pick_head(the_repository);
3680 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3681 return error(_("could not remove CHERRY_PICK_HEAD"));
3682 if (!final_fixup)
3683 return 0;
3686 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3687 opts, flags))
3688 return error(_("could not commit staged changes."));
3689 unlink(rebase_path_amend());
3690 if (final_fixup) {
3691 unlink(rebase_path_fixup_msg());
3692 unlink(rebase_path_squash_msg());
3694 if (opts->current_fixup_count > 0) {
3696 * Whether final fixup or not, we just cleaned up the commit
3697 * message...
3699 unlink(rebase_path_current_fixups());
3700 strbuf_reset(&opts->current_fixups);
3701 opts->current_fixup_count = 0;
3703 return 0;
3706 int sequencer_continue(struct replay_opts *opts)
3708 struct todo_list todo_list = TODO_LIST_INIT;
3709 int res;
3711 if (read_and_refresh_cache(opts))
3712 return -1;
3714 if (read_populate_opts(opts))
3715 return -1;
3716 if (is_rebase_i(opts)) {
3717 if ((res = read_populate_todo(&todo_list, opts)))
3718 goto release_todo_list;
3719 if (commit_staged_changes(opts, &todo_list))
3720 return -1;
3721 } else if (!file_exists(get_todo_path(opts)))
3722 return continue_single_pick();
3723 else if ((res = read_populate_todo(&todo_list, opts)))
3724 goto release_todo_list;
3726 if (!is_rebase_i(opts)) {
3727 /* Verify that the conflict has been resolved */
3728 if (file_exists(git_path_cherry_pick_head(the_repository)) ||
3729 file_exists(git_path_revert_head(the_repository))) {
3730 res = continue_single_pick();
3731 if (res)
3732 goto release_todo_list;
3734 if (index_differs_from("HEAD", NULL, 0)) {
3735 res = error_dirty_index(opts);
3736 goto release_todo_list;
3738 todo_list.current++;
3739 } else if (file_exists(rebase_path_stopped_sha())) {
3740 struct strbuf buf = STRBUF_INIT;
3741 struct object_id oid;
3743 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3744 !get_oid_committish(buf.buf, &oid))
3745 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3746 strbuf_release(&buf);
3749 res = pick_commits(&todo_list, opts);
3750 release_todo_list:
3751 todo_list_release(&todo_list);
3752 return res;
3755 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3757 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3758 return do_pick_commit(opts->action == REPLAY_PICK ?
3759 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3762 int sequencer_pick_revisions(struct replay_opts *opts)
3764 struct todo_list todo_list = TODO_LIST_INIT;
3765 struct object_id oid;
3766 int i, res;
3768 assert(opts->revs);
3769 if (read_and_refresh_cache(opts))
3770 return -1;
3772 for (i = 0; i < opts->revs->pending.nr; i++) {
3773 struct object_id oid;
3774 const char *name = opts->revs->pending.objects[i].name;
3776 /* This happens when using --stdin. */
3777 if (!strlen(name))
3778 continue;
3780 if (!get_oid(name, &oid)) {
3781 if (!lookup_commit_reference_gently(the_repository, &oid, 1)) {
3782 enum object_type type = oid_object_info(the_repository,
3783 &oid,
3784 NULL);
3785 return error(_("%s: can't cherry-pick a %s"),
3786 name, type_name(type));
3788 } else
3789 return error(_("%s: bad revision"), name);
3793 * If we were called as "git cherry-pick <commit>", just
3794 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3795 * REVERT_HEAD, and don't touch the sequencer state.
3796 * This means it is possible to cherry-pick in the middle
3797 * of a cherry-pick sequence.
3799 if (opts->revs->cmdline.nr == 1 &&
3800 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3801 opts->revs->no_walk &&
3802 !opts->revs->cmdline.rev->flags) {
3803 struct commit *cmit;
3804 if (prepare_revision_walk(opts->revs))
3805 return error(_("revision walk setup failed"));
3806 cmit = get_revision(opts->revs);
3807 if (!cmit)
3808 return error(_("empty commit set passed"));
3809 if (get_revision(opts->revs))
3810 BUG("unexpected extra commit from walk");
3811 return single_pick(cmit, opts);
3815 * Start a new cherry-pick/ revert sequence; but
3816 * first, make sure that an existing one isn't in
3817 * progress
3820 if (walk_revs_populate_todo(&todo_list, opts) ||
3821 create_seq_dir() < 0)
3822 return -1;
3823 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3824 return error(_("can't revert as initial commit"));
3825 if (save_head(oid_to_hex(&oid)))
3826 return -1;
3827 if (save_opts(opts))
3828 return -1;
3829 update_abort_safety_file();
3830 res = pick_commits(&todo_list, opts);
3831 todo_list_release(&todo_list);
3832 return res;
3835 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
3837 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3838 struct strbuf sob = STRBUF_INIT;
3839 int has_footer;
3841 strbuf_addstr(&sob, sign_off_header);
3842 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3843 getenv("GIT_COMMITTER_EMAIL")));
3844 strbuf_addch(&sob, '\n');
3846 if (!ignore_footer)
3847 strbuf_complete_line(msgbuf);
3850 * If the whole message buffer is equal to the sob, pretend that we
3851 * found a conforming footer with a matching sob
3853 if (msgbuf->len - ignore_footer == sob.len &&
3854 !strncmp(msgbuf->buf, sob.buf, sob.len))
3855 has_footer = 3;
3856 else
3857 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3859 if (!has_footer) {
3860 const char *append_newlines = NULL;
3861 size_t len = msgbuf->len - ignore_footer;
3863 if (!len) {
3865 * The buffer is completely empty. Leave foom for
3866 * the title and body to be filled in by the user.
3868 append_newlines = "\n\n";
3869 } else if (len == 1) {
3871 * Buffer contains a single newline. Add another
3872 * so that we leave room for the title and body.
3874 append_newlines = "\n";
3875 } else if (msgbuf->buf[len - 2] != '\n') {
3877 * Buffer ends with a single newline. Add another
3878 * so that there is an empty line between the message
3879 * body and the sob.
3881 append_newlines = "\n";
3882 } /* else, the buffer already ends with two newlines. */
3884 if (append_newlines)
3885 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3886 append_newlines, strlen(append_newlines));
3889 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3890 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3891 sob.buf, sob.len);
3893 strbuf_release(&sob);
3896 struct labels_entry {
3897 struct hashmap_entry entry;
3898 char label[FLEX_ARRAY];
3901 static int labels_cmp(const void *fndata, const struct labels_entry *a,
3902 const struct labels_entry *b, const void *key)
3904 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3907 struct string_entry {
3908 struct oidmap_entry entry;
3909 char string[FLEX_ARRAY];
3912 struct label_state {
3913 struct oidmap commit2label;
3914 struct hashmap labels;
3915 struct strbuf buf;
3918 static const char *label_oid(struct object_id *oid, const char *label,
3919 struct label_state *state)
3921 struct labels_entry *labels_entry;
3922 struct string_entry *string_entry;
3923 struct object_id dummy;
3924 size_t len;
3925 int i;
3927 string_entry = oidmap_get(&state->commit2label, oid);
3928 if (string_entry)
3929 return string_entry->string;
3932 * For "uninteresting" commits, i.e. commits that are not to be
3933 * rebased, and which can therefore not be labeled, we use a unique
3934 * abbreviation of the commit name. This is slightly more complicated
3935 * than calling find_unique_abbrev() because we also need to make
3936 * sure that the abbreviation does not conflict with any other
3937 * label.
3939 * We disallow "interesting" commits to be labeled by a string that
3940 * is a valid full-length hash, to ensure that we always can find an
3941 * abbreviation for any uninteresting commit's names that does not
3942 * clash with any other label.
3944 if (!label) {
3945 char *p;
3947 strbuf_reset(&state->buf);
3948 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3949 label = p = state->buf.buf;
3951 find_unique_abbrev_r(p, oid, default_abbrev);
3954 * We may need to extend the abbreviated hash so that there is
3955 * no conflicting label.
3957 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3958 size_t i = strlen(p) + 1;
3960 oid_to_hex_r(p, oid);
3961 for (; i < GIT_SHA1_HEXSZ; i++) {
3962 char save = p[i];
3963 p[i] = '\0';
3964 if (!hashmap_get_from_hash(&state->labels,
3965 strihash(p), p))
3966 break;
3967 p[i] = save;
3970 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
3971 !get_oid_hex(label, &dummy)) ||
3972 (len == 1 && *label == '#') ||
3973 hashmap_get_from_hash(&state->labels,
3974 strihash(label), label)) {
3976 * If the label already exists, or if the label is a valid full
3977 * OID, or the label is a '#' (which we use as a separator
3978 * between merge heads and oneline), we append a dash and a
3979 * number to make it unique.
3981 struct strbuf *buf = &state->buf;
3983 strbuf_reset(buf);
3984 strbuf_add(buf, label, len);
3986 for (i = 2; ; i++) {
3987 strbuf_setlen(buf, len);
3988 strbuf_addf(buf, "-%d", i);
3989 if (!hashmap_get_from_hash(&state->labels,
3990 strihash(buf->buf),
3991 buf->buf))
3992 break;
3995 label = buf->buf;
3998 FLEX_ALLOC_STR(labels_entry, label, label);
3999 hashmap_entry_init(labels_entry, strihash(label));
4000 hashmap_add(&state->labels, labels_entry);
4002 FLEX_ALLOC_STR(string_entry, string, label);
4003 oidcpy(&string_entry->entry.oid, oid);
4004 oidmap_put(&state->commit2label, string_entry);
4006 return string_entry->string;
4009 static int make_script_with_merges(struct pretty_print_context *pp,
4010 struct rev_info *revs, FILE *out,
4011 unsigned flags)
4013 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4014 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4015 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4016 struct strbuf label = STRBUF_INIT;
4017 struct commit_list *commits = NULL, **tail = &commits, *iter;
4018 struct commit_list *tips = NULL, **tips_tail = &tips;
4019 struct commit *commit;
4020 struct oidmap commit2todo = OIDMAP_INIT;
4021 struct string_entry *entry;
4022 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4023 shown = OIDSET_INIT;
4024 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4026 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4027 const char *cmd_pick = abbr ? "p" : "pick",
4028 *cmd_label = abbr ? "l" : "label",
4029 *cmd_reset = abbr ? "t" : "reset",
4030 *cmd_merge = abbr ? "m" : "merge";
4032 oidmap_init(&commit2todo, 0);
4033 oidmap_init(&state.commit2label, 0);
4034 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4035 strbuf_init(&state.buf, 32);
4037 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4038 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4039 FLEX_ALLOC_STR(entry, string, "onto");
4040 oidcpy(&entry->entry.oid, oid);
4041 oidmap_put(&state.commit2label, entry);
4045 * First phase:
4046 * - get onelines for all commits
4047 * - gather all branch tips (i.e. 2nd or later parents of merges)
4048 * - label all branch tips
4050 while ((commit = get_revision(revs))) {
4051 struct commit_list *to_merge;
4052 const char *p1, *p2;
4053 struct object_id *oid;
4054 int is_empty;
4056 tail = &commit_list_insert(commit, tail)->next;
4057 oidset_insert(&interesting, &commit->object.oid);
4059 is_empty = is_original_commit_empty(commit);
4060 if (!is_empty && (commit->object.flags & PATCHSAME))
4061 continue;
4063 strbuf_reset(&oneline);
4064 pretty_print_commit(pp, commit, &oneline);
4066 to_merge = commit->parents ? commit->parents->next : NULL;
4067 if (!to_merge) {
4068 /* non-merge commit: easy case */
4069 strbuf_reset(&buf);
4070 if (!keep_empty && is_empty)
4071 strbuf_addf(&buf, "%c ", comment_line_char);
4072 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4073 oid_to_hex(&commit->object.oid),
4074 oneline.buf);
4076 FLEX_ALLOC_STR(entry, string, buf.buf);
4077 oidcpy(&entry->entry.oid, &commit->object.oid);
4078 oidmap_put(&commit2todo, entry);
4080 continue;
4083 /* Create a label */
4084 strbuf_reset(&label);
4085 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4086 (p1 = strchr(p1, '\'')) &&
4087 (p2 = strchr(++p1, '\'')))
4088 strbuf_add(&label, p1, p2 - p1);
4089 else if (skip_prefix(oneline.buf, "Merge pull request ",
4090 &p1) &&
4091 (p1 = strstr(p1, " from ")))
4092 strbuf_addstr(&label, p1 + strlen(" from "));
4093 else
4094 strbuf_addbuf(&label, &oneline);
4096 for (p1 = label.buf; *p1; p1++)
4097 if (isspace(*p1))
4098 *(char *)p1 = '-';
4100 strbuf_reset(&buf);
4101 strbuf_addf(&buf, "%s -C %s",
4102 cmd_merge, oid_to_hex(&commit->object.oid));
4104 /* label the tips of merged branches */
4105 for (; to_merge; to_merge = to_merge->next) {
4106 oid = &to_merge->item->object.oid;
4107 strbuf_addch(&buf, ' ');
4109 if (!oidset_contains(&interesting, oid)) {
4110 strbuf_addstr(&buf, label_oid(oid, NULL,
4111 &state));
4112 continue;
4115 tips_tail = &commit_list_insert(to_merge->item,
4116 tips_tail)->next;
4118 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4120 strbuf_addf(&buf, " # %s", oneline.buf);
4122 FLEX_ALLOC_STR(entry, string, buf.buf);
4123 oidcpy(&entry->entry.oid, &commit->object.oid);
4124 oidmap_put(&commit2todo, entry);
4128 * Second phase:
4129 * - label branch points
4130 * - add HEAD to the branch tips
4132 for (iter = commits; iter; iter = iter->next) {
4133 struct commit_list *parent = iter->item->parents;
4134 for (; parent; parent = parent->next) {
4135 struct object_id *oid = &parent->item->object.oid;
4136 if (!oidset_contains(&interesting, oid))
4137 continue;
4138 if (!oidset_contains(&child_seen, oid))
4139 oidset_insert(&child_seen, oid);
4140 else
4141 label_oid(oid, "branch-point", &state);
4144 /* Add HEAD as implict "tip of branch" */
4145 if (!iter->next)
4146 tips_tail = &commit_list_insert(iter->item,
4147 tips_tail)->next;
4151 * Third phase: output the todo list. This is a bit tricky, as we
4152 * want to avoid jumping back and forth between revisions. To
4153 * accomplish that goal, we walk backwards from the branch tips,
4154 * gathering commits not yet shown, reversing the list on the fly,
4155 * then outputting that list (labeling revisions as needed).
4157 fprintf(out, "%s onto\n", cmd_label);
4158 for (iter = tips; iter; iter = iter->next) {
4159 struct commit_list *list = NULL, *iter2;
4161 commit = iter->item;
4162 if (oidset_contains(&shown, &commit->object.oid))
4163 continue;
4164 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4166 if (entry)
4167 fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4168 else
4169 fprintf(out, "\n");
4171 while (oidset_contains(&interesting, &commit->object.oid) &&
4172 !oidset_contains(&shown, &commit->object.oid)) {
4173 commit_list_insert(commit, &list);
4174 if (!commit->parents) {
4175 commit = NULL;
4176 break;
4178 commit = commit->parents->item;
4181 if (!commit)
4182 fprintf(out, "%s %s\n", cmd_reset,
4183 rebase_cousins ? "onto" : "[new root]");
4184 else {
4185 const char *to = NULL;
4187 entry = oidmap_get(&state.commit2label,
4188 &commit->object.oid);
4189 if (entry)
4190 to = entry->string;
4191 else if (!rebase_cousins)
4192 to = label_oid(&commit->object.oid, NULL,
4193 &state);
4195 if (!to || !strcmp(to, "onto"))
4196 fprintf(out, "%s onto\n", cmd_reset);
4197 else {
4198 strbuf_reset(&oneline);
4199 pretty_print_commit(pp, commit, &oneline);
4200 fprintf(out, "%s %s # %s\n",
4201 cmd_reset, to, oneline.buf);
4205 for (iter2 = list; iter2; iter2 = iter2->next) {
4206 struct object_id *oid = &iter2->item->object.oid;
4207 entry = oidmap_get(&commit2todo, oid);
4208 /* only show if not already upstream */
4209 if (entry)
4210 fprintf(out, "%s\n", entry->string);
4211 entry = oidmap_get(&state.commit2label, oid);
4212 if (entry)
4213 fprintf(out, "%s %s\n",
4214 cmd_label, entry->string);
4215 oidset_insert(&shown, oid);
4218 free_commit_list(list);
4221 free_commit_list(commits);
4222 free_commit_list(tips);
4224 strbuf_release(&label);
4225 strbuf_release(&oneline);
4226 strbuf_release(&buf);
4228 oidmap_free(&commit2todo, 1);
4229 oidmap_free(&state.commit2label, 1);
4230 hashmap_free(&state.labels, 1);
4231 strbuf_release(&state.buf);
4233 return 0;
4236 int sequencer_make_script(FILE *out, int argc, const char **argv,
4237 unsigned flags)
4239 char *format = NULL;
4240 struct pretty_print_context pp = {0};
4241 struct strbuf buf = STRBUF_INIT;
4242 struct rev_info revs;
4243 struct commit *commit;
4244 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4245 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4246 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4248 init_revisions(&revs, NULL);
4249 revs.verbose_header = 1;
4250 if (!rebase_merges)
4251 revs.max_parents = 1;
4252 revs.cherry_mark = 1;
4253 revs.limited = 1;
4254 revs.reverse = 1;
4255 revs.right_only = 1;
4256 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4257 revs.topo_order = 1;
4259 revs.pretty_given = 1;
4260 git_config_get_string("rebase.instructionFormat", &format);
4261 if (!format || !*format) {
4262 free(format);
4263 format = xstrdup("%s");
4265 get_commit_format(format, &revs);
4266 free(format);
4267 pp.fmt = revs.commit_format;
4268 pp.output_encoding = get_log_output_encoding();
4270 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4271 return error(_("make_script: unhandled options"));
4273 if (prepare_revision_walk(&revs) < 0)
4274 return error(_("make_script: error preparing revisions"));
4276 if (rebase_merges)
4277 return make_script_with_merges(&pp, &revs, out, flags);
4279 while ((commit = get_revision(&revs))) {
4280 int is_empty = is_original_commit_empty(commit);
4282 if (!is_empty && (commit->object.flags & PATCHSAME))
4283 continue;
4284 strbuf_reset(&buf);
4285 if (!keep_empty && is_empty)
4286 strbuf_addf(&buf, "%c ", comment_line_char);
4287 strbuf_addf(&buf, "%s %s ", insn,
4288 oid_to_hex(&commit->object.oid));
4289 pretty_print_commit(&pp, commit, &buf);
4290 strbuf_addch(&buf, '\n');
4291 fputs(buf.buf, out);
4293 strbuf_release(&buf);
4294 return 0;
4298 * Add commands after pick and (series of) squash/fixup commands
4299 * in the todo list.
4301 int sequencer_add_exec_commands(const char *commands)
4303 const char *todo_file = rebase_path_todo();
4304 struct todo_list todo_list = TODO_LIST_INIT;
4305 struct strbuf *buf = &todo_list.buf;
4306 size_t offset = 0, commands_len = strlen(commands);
4307 int i, insert;
4309 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4310 return error(_("could not read '%s'."), todo_file);
4312 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4313 todo_list_release(&todo_list);
4314 return error(_("unusable todo list: '%s'"), todo_file);
4318 * Insert <commands> after every pick. Here, fixup/squash chains
4319 * are considered part of the pick, so we insert the commands *after*
4320 * those chains if there are any.
4322 insert = -1;
4323 for (i = 0; i < todo_list.nr; i++) {
4324 enum todo_command command = todo_list.items[i].command;
4326 if (insert >= 0) {
4327 /* skip fixup/squash chains */
4328 if (command == TODO_COMMENT)
4329 continue;
4330 else if (is_fixup(command)) {
4331 insert = i + 1;
4332 continue;
4334 strbuf_insert(buf,
4335 todo_list.items[insert].offset_in_buf +
4336 offset, commands, commands_len);
4337 offset += commands_len;
4338 insert = -1;
4341 if (command == TODO_PICK || command == TODO_MERGE)
4342 insert = i + 1;
4345 /* insert or append final <commands> */
4346 if (insert >= 0 && insert < todo_list.nr)
4347 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4348 offset, commands, commands_len);
4349 else if (insert >= 0 || !offset)
4350 strbuf_add(buf, commands, commands_len);
4352 i = write_message(buf->buf, buf->len, todo_file, 0);
4353 todo_list_release(&todo_list);
4354 return i;
4357 int transform_todos(unsigned flags)
4359 const char *todo_file = rebase_path_todo();
4360 struct todo_list todo_list = TODO_LIST_INIT;
4361 struct strbuf buf = STRBUF_INIT;
4362 struct todo_item *item;
4363 int i;
4365 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4366 return error(_("could not read '%s'."), todo_file);
4368 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4369 todo_list_release(&todo_list);
4370 return error(_("unusable todo list: '%s'"), todo_file);
4373 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4374 /* if the item is not a command write it and continue */
4375 if (item->command >= TODO_COMMENT) {
4376 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4377 continue;
4380 /* add command to the buffer */
4381 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4382 strbuf_addch(&buf, command_to_char(item->command));
4383 else
4384 strbuf_addstr(&buf, command_to_string(item->command));
4386 /* add commit id */
4387 if (item->commit) {
4388 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4389 short_commit_name(item->commit) :
4390 oid_to_hex(&item->commit->object.oid);
4392 if (item->command == TODO_MERGE) {
4393 if (item->flags & TODO_EDIT_MERGE_MSG)
4394 strbuf_addstr(&buf, " -c");
4395 else
4396 strbuf_addstr(&buf, " -C");
4399 strbuf_addf(&buf, " %s", oid);
4402 /* add all the rest */
4403 if (!item->arg_len)
4404 strbuf_addch(&buf, '\n');
4405 else
4406 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4409 i = write_message(buf.buf, buf.len, todo_file, 0);
4410 todo_list_release(&todo_list);
4411 return i;
4414 enum check_level {
4415 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
4418 static enum check_level get_missing_commit_check_level(void)
4420 const char *value;
4422 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4423 !strcasecmp("ignore", value))
4424 return CHECK_IGNORE;
4425 if (!strcasecmp("warn", value))
4426 return CHECK_WARN;
4427 if (!strcasecmp("error", value))
4428 return CHECK_ERROR;
4429 warning(_("unrecognized setting %s for option "
4430 "rebase.missingCommitsCheck. Ignoring."), value);
4431 return CHECK_IGNORE;
4434 define_commit_slab(commit_seen, unsigned char);
4436 * Check if the user dropped some commits by mistake
4437 * Behaviour determined by rebase.missingCommitsCheck.
4438 * Check if there is an unrecognized command or a
4439 * bad SHA-1 in a command.
4441 int check_todo_list(void)
4443 enum check_level check_level = get_missing_commit_check_level();
4444 struct strbuf todo_file = STRBUF_INIT;
4445 struct todo_list todo_list = TODO_LIST_INIT;
4446 struct strbuf missing = STRBUF_INIT;
4447 int advise_to_edit_todo = 0, res = 0, i;
4448 struct commit_seen commit_seen;
4450 init_commit_seen(&commit_seen);
4452 strbuf_addstr(&todo_file, rebase_path_todo());
4453 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4454 res = -1;
4455 goto leave_check;
4457 advise_to_edit_todo = res =
4458 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4460 if (res || check_level == CHECK_IGNORE)
4461 goto leave_check;
4463 /* Mark the commits in git-rebase-todo as seen */
4464 for (i = 0; i < todo_list.nr; i++) {
4465 struct commit *commit = todo_list.items[i].commit;
4466 if (commit)
4467 *commit_seen_at(&commit_seen, commit) = 1;
4470 todo_list_release(&todo_list);
4471 strbuf_addstr(&todo_file, ".backup");
4472 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4473 res = -1;
4474 goto leave_check;
4476 strbuf_release(&todo_file);
4477 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4479 /* Find commits in git-rebase-todo.backup yet unseen */
4480 for (i = todo_list.nr - 1; i >= 0; i--) {
4481 struct todo_item *item = todo_list.items + i;
4482 struct commit *commit = item->commit;
4483 if (commit && !*commit_seen_at(&commit_seen, commit)) {
4484 strbuf_addf(&missing, " - %s %.*s\n",
4485 short_commit_name(commit),
4486 item->arg_len, item->arg);
4487 *commit_seen_at(&commit_seen, commit) = 1;
4491 /* Warn about missing commits */
4492 if (!missing.len)
4493 goto leave_check;
4495 if (check_level == CHECK_ERROR)
4496 advise_to_edit_todo = res = 1;
4498 fprintf(stderr,
4499 _("Warning: some commits may have been dropped accidentally.\n"
4500 "Dropped commits (newer to older):\n"));
4502 /* Make the list user-friendly and display */
4503 fputs(missing.buf, stderr);
4504 strbuf_release(&missing);
4506 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4507 "explicitly remove a commit.\n\n"
4508 "Use 'git config rebase.missingCommitsCheck' to change "
4509 "the level of warnings.\n"
4510 "The possible behaviours are: ignore, warn, error.\n\n"));
4512 leave_check:
4513 clear_commit_seen(&commit_seen);
4514 strbuf_release(&todo_file);
4515 todo_list_release(&todo_list);
4517 if (advise_to_edit_todo)
4518 fprintf(stderr,
4519 _("You can fix this with 'git rebase --edit-todo' "
4520 "and then run 'git rebase --continue'.\n"
4521 "Or you can abort the rebase with 'git rebase"
4522 " --abort'.\n"));
4524 return res;
4527 static int rewrite_file(const char *path, const char *buf, size_t len)
4529 int rc = 0;
4530 int fd = open(path, O_WRONLY | O_TRUNC);
4531 if (fd < 0)
4532 return error_errno(_("could not open '%s' for writing"), path);
4533 if (write_in_full(fd, buf, len) < 0)
4534 rc = error_errno(_("could not write to '%s'"), path);
4535 if (close(fd) && !rc)
4536 rc = error_errno(_("could not close '%s'"), path);
4537 return rc;
4540 /* skip picking commits whose parents are unchanged */
4541 int skip_unnecessary_picks(void)
4543 const char *todo_file = rebase_path_todo();
4544 struct strbuf buf = STRBUF_INIT;
4545 struct todo_list todo_list = TODO_LIST_INIT;
4546 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4547 int fd, i;
4549 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4550 return error(_("could not read 'onto'"));
4551 if (get_oid(buf.buf, &onto_oid)) {
4552 strbuf_release(&buf);
4553 return error(_("need a HEAD to fixup"));
4555 strbuf_release(&buf);
4557 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4558 return -1;
4559 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4560 todo_list_release(&todo_list);
4561 return -1;
4564 for (i = 0; i < todo_list.nr; i++) {
4565 struct todo_item *item = todo_list.items + i;
4567 if (item->command >= TODO_NOOP)
4568 continue;
4569 if (item->command != TODO_PICK)
4570 break;
4571 if (parse_commit(item->commit)) {
4572 todo_list_release(&todo_list);
4573 return error(_("could not parse commit '%s'"),
4574 oid_to_hex(&item->commit->object.oid));
4576 if (!item->commit->parents)
4577 break; /* root commit */
4578 if (item->commit->parents->next)
4579 break; /* merge commit */
4580 parent_oid = &item->commit->parents->item->object.oid;
4581 if (!oideq(parent_oid, oid))
4582 break;
4583 oid = &item->commit->object.oid;
4585 if (i > 0) {
4586 int offset = get_item_line_offset(&todo_list, i);
4587 const char *done_path = rebase_path_done();
4589 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4590 if (fd < 0) {
4591 error_errno(_("could not open '%s' for writing"),
4592 done_path);
4593 todo_list_release(&todo_list);
4594 return -1;
4596 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4597 error_errno(_("could not write to '%s'"), done_path);
4598 todo_list_release(&todo_list);
4599 close(fd);
4600 return -1;
4602 close(fd);
4604 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4605 todo_list.buf.len - offset) < 0) {
4606 todo_list_release(&todo_list);
4607 return -1;
4610 todo_list.current = i;
4611 if (is_fixup(peek_command(&todo_list, 0)))
4612 record_in_rewritten(oid, peek_command(&todo_list, 0));
4615 todo_list_release(&todo_list);
4616 printf("%s\n", oid_to_hex(oid));
4618 return 0;
4621 struct subject2item_entry {
4622 struct hashmap_entry entry;
4623 int i;
4624 char subject[FLEX_ARRAY];
4627 static int subject2item_cmp(const void *fndata,
4628 const struct subject2item_entry *a,
4629 const struct subject2item_entry *b, const void *key)
4631 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4634 define_commit_slab(commit_todo_item, struct todo_item *);
4637 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4638 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4639 * after the former, and change "pick" to "fixup"/"squash".
4641 * Note that if the config has specified a custom instruction format, each log
4642 * message will have to be retrieved from the commit (as the oneline in the
4643 * script cannot be trusted) in order to normalize the autosquash arrangement.
4645 int rearrange_squash(void)
4647 const char *todo_file = rebase_path_todo();
4648 struct todo_list todo_list = TODO_LIST_INIT;
4649 struct hashmap subject2item;
4650 int res = 0, rearranged = 0, *next, *tail, i;
4651 char **subjects;
4652 struct commit_todo_item commit_todo;
4654 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4655 return -1;
4656 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4657 todo_list_release(&todo_list);
4658 return -1;
4661 init_commit_todo_item(&commit_todo);
4663 * The hashmap maps onelines to the respective todo list index.
4665 * If any items need to be rearranged, the next[i] value will indicate
4666 * which item was moved directly after the i'th.
4668 * In that case, last[i] will indicate the index of the latest item to
4669 * be moved to appear after the i'th.
4671 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4672 NULL, todo_list.nr);
4673 ALLOC_ARRAY(next, todo_list.nr);
4674 ALLOC_ARRAY(tail, todo_list.nr);
4675 ALLOC_ARRAY(subjects, todo_list.nr);
4676 for (i = 0; i < todo_list.nr; i++) {
4677 struct strbuf buf = STRBUF_INIT;
4678 struct todo_item *item = todo_list.items + i;
4679 const char *commit_buffer, *subject, *p;
4680 size_t subject_len;
4681 int i2 = -1;
4682 struct subject2item_entry *entry;
4684 next[i] = tail[i] = -1;
4685 if (!item->commit || item->command == TODO_DROP) {
4686 subjects[i] = NULL;
4687 continue;
4690 if (is_fixup(item->command)) {
4691 todo_list_release(&todo_list);
4692 clear_commit_todo_item(&commit_todo);
4693 return error(_("the script was already rearranged."));
4696 *commit_todo_item_at(&commit_todo, item->commit) = item;
4698 parse_commit(item->commit);
4699 commit_buffer = get_commit_buffer(item->commit, NULL);
4700 find_commit_subject(commit_buffer, &subject);
4701 format_subject(&buf, subject, " ");
4702 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4703 unuse_commit_buffer(item->commit, commit_buffer);
4704 if ((skip_prefix(subject, "fixup! ", &p) ||
4705 skip_prefix(subject, "squash! ", &p))) {
4706 struct commit *commit2;
4708 for (;;) {
4709 while (isspace(*p))
4710 p++;
4711 if (!skip_prefix(p, "fixup! ", &p) &&
4712 !skip_prefix(p, "squash! ", &p))
4713 break;
4716 if ((entry = hashmap_get_from_hash(&subject2item,
4717 strhash(p), p)))
4718 /* found by title */
4719 i2 = entry->i;
4720 else if (!strchr(p, ' ') &&
4721 (commit2 =
4722 lookup_commit_reference_by_name(p)) &&
4723 *commit_todo_item_at(&commit_todo, commit2))
4724 /* found by commit name */
4725 i2 = *commit_todo_item_at(&commit_todo, commit2)
4726 - todo_list.items;
4727 else {
4728 /* copy can be a prefix of the commit subject */
4729 for (i2 = 0; i2 < i; i2++)
4730 if (subjects[i2] &&
4731 starts_with(subjects[i2], p))
4732 break;
4733 if (i2 == i)
4734 i2 = -1;
4737 if (i2 >= 0) {
4738 rearranged = 1;
4739 todo_list.items[i].command =
4740 starts_with(subject, "fixup!") ?
4741 TODO_FIXUP : TODO_SQUASH;
4742 if (next[i2] < 0)
4743 next[i2] = i;
4744 else
4745 next[tail[i2]] = i;
4746 tail[i2] = i;
4747 } else if (!hashmap_get_from_hash(&subject2item,
4748 strhash(subject), subject)) {
4749 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4750 entry->i = i;
4751 hashmap_entry_init(entry, strhash(entry->subject));
4752 hashmap_put(&subject2item, entry);
4756 if (rearranged) {
4757 struct strbuf buf = STRBUF_INIT;
4759 for (i = 0; i < todo_list.nr; i++) {
4760 enum todo_command command = todo_list.items[i].command;
4761 int cur = i;
4764 * Initially, all commands are 'pick's. If it is a
4765 * fixup or a squash now, we have rearranged it.
4767 if (is_fixup(command))
4768 continue;
4770 while (cur >= 0) {
4771 const char *bol =
4772 get_item_line(&todo_list, cur);
4773 const char *eol =
4774 get_item_line(&todo_list, cur + 1);
4776 /* replace 'pick', by 'fixup' or 'squash' */
4777 command = todo_list.items[cur].command;
4778 if (is_fixup(command)) {
4779 strbuf_addstr(&buf,
4780 todo_command_info[command].str);
4781 bol += strcspn(bol, " \t");
4784 strbuf_add(&buf, bol, eol - bol);
4786 cur = next[cur];
4790 res = rewrite_file(todo_file, buf.buf, buf.len);
4791 strbuf_release(&buf);
4794 free(next);
4795 free(tail);
4796 for (i = 0; i < todo_list.nr; i++)
4797 free(subjects[i]);
4798 free(subjects);
4799 hashmap_free(&subject2item, 1);
4800 todo_list_release(&todo_list);
4802 clear_commit_todo_item(&commit_todo);
4803 return res;