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