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