173949602e444b41478de66c71d84550b42bc3f2
   1#include "cache.h"
   2#include "config.h"
   3#include "lockfile.h"
   4#include "sequencer.h"
   5#include "dir.h"
   6#include "object.h"
   7#include "commit.h"
   8#include "tag.h"
   9#include "run-command.h"
  10#include "exec_cmd.h"
  11#include "utf8.h"
  12#include "cache-tree.h"
  13#include "diff.h"
  14#include "revision.h"
  15#include "rerere.h"
  16#include "merge-recursive.h"
  17#include "refs.h"
  18#include "argv-array.h"
  19#include "quote.h"
  20#include "trailer.h"
  21#include "log-tree.h"
  22#include "wt-status.h"
  23#include "hashmap.h"
  24#include "unpack-trees.h"
  25#include "worktree.h"
  26
  27#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  28
  29const char sign_off_header[] = "Signed-off-by: ";
  30static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  31
  32GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  33
  34static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  35static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  36static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  37static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  38
  39static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  40/*
  41 * The file containing rebase commands, comments, and empty lines.
  42 * This file is created by "git rebase -i" then edited by the user. As
  43 * the lines are processed, they are removed from the front of this
  44 * file and written to the tail of 'done'.
  45 */
  46static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  47/*
  48 * The rebase command lines that have already been processed. A line
  49 * is moved here when it is first handled, before any associated user
  50 * actions.
  51 */
  52static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  53/*
  54 * The file to keep track of how many commands were already processed (e.g.
  55 * for the prompt).
  56 */
  57static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
  58/*
  59 * The file to keep track of how many commands are to be processed in total
  60 * (e.g. for the prompt).
  61 */
  62static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
  63/*
  64 * The commit message that is planned to be used for any changes that
  65 * need to be committed following a user interaction.
  66 */
  67static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  68/*
  69 * The file into which is accumulated the suggested commit message for
  70 * squash/fixup commands. When the first of a series of squash/fixups
  71 * is seen, the file is created and the commit message from the
  72 * previous commit and from the first squash/fixup commit are written
  73 * to it. The commit message for each subsequent squash/fixup commit
  74 * is appended to the file as it is processed.
  75 *
  76 * The first line of the file is of the form
  77 *     # This is a combination of $count commits.
  78 * where $count is the number of commits whose messages have been
  79 * written to the file so far (including the initial "pick" commit).
  80 * Each time that a commit message is processed, this line is read and
  81 * updated. It is deleted just before the combined commit is made.
  82 */
  83static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
  84/*
  85 * If the current series of squash/fixups has not yet included a squash
  86 * command, then this file exists and holds the commit message of the
  87 * original "pick" commit.  (If the series ends without a "squash"
  88 * command, then this can be used as the commit message of the combined
  89 * commit without opening the editor.)
  90 */
  91static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
  92/*
  93 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  94 * GIT_AUTHOR_DATE that will be used for the commit that is currently
  95 * being rebased.
  96 */
  97static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  98/*
  99 * When an "edit" rebase command is being processed, the SHA1 of the
 100 * commit to be edited is recorded in this file.  When "git rebase
 101 * --continue" is executed, if there are any staged changes then they
 102 * will be amended to the HEAD commit, but only provided the HEAD
 103 * commit is still the commit to be edited.  When any other rebase
 104 * command is processed, this file is deleted.
 105 */
 106static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
 107/*
 108 * When we stop at a given patch via the "edit" command, this file contains
 109 * the abbreviated commit name of the corresponding patch.
 110 */
 111static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
 112/*
 113 * For the post-rewrite hook, we make a list of rewritten commits and
 114 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 115 * commits that have been processed, but not committed yet,
 116 * e.g. because they are waiting for a 'squash' command.
 117 */
 118static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
 119static GIT_PATH_FUNC(rebase_path_rewritten_pending,
 120        "rebase-merge/rewritten-pending")
 121
 122/*
 123 * The path of the file listing refs that need to be deleted after the rebase
 124 * finishes. This is used by the `label` command to record the need for cleanup.
 125 */
 126static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
 127
 128/*
 129 * The following files are written by git-rebase just after parsing the
 130 * command-line (and are only consumed, not modified, by the sequencer).
 131 */
 132static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
 133static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
 134static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
 135static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
 136static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
 137static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
 138static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
 139static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
 140static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
 141
 142static inline int is_rebase_i(const struct replay_opts *opts)
 143{
 144        return opts->action == REPLAY_INTERACTIVE_REBASE;
 145}
 146
 147static const char *get_dir(const struct replay_opts *opts)
 148{
 149        if (is_rebase_i(opts))
 150                return rebase_path();
 151        return git_path_seq_dir();
 152}
 153
 154static const char *get_todo_path(const struct replay_opts *opts)
 155{
 156        if (is_rebase_i(opts))
 157                return rebase_path_todo();
 158        return git_path_todo_file();
 159}
 160
 161/*
 162 * Returns 0 for non-conforming footer
 163 * Returns 1 for conforming footer
 164 * Returns 2 when sob exists within conforming footer
 165 * Returns 3 when sob exists within conforming footer as last entry
 166 */
 167static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
 168        int ignore_footer)
 169{
 170        struct trailer_info info;
 171        int i;
 172        int found_sob = 0, found_sob_last = 0;
 173
 174        trailer_info_get(&info, sb->buf);
 175
 176        if (info.trailer_start == info.trailer_end)
 177                return 0;
 178
 179        for (i = 0; i < info.trailer_nr; i++)
 180                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 181                        found_sob = 1;
 182                        if (i == info.trailer_nr - 1)
 183                                found_sob_last = 1;
 184                }
 185
 186        trailer_info_release(&info);
 187
 188        if (found_sob_last)
 189                return 3;
 190        if (found_sob)
 191                return 2;
 192        return 1;
 193}
 194
 195static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 196{
 197        static struct strbuf buf = STRBUF_INIT;
 198
 199        strbuf_reset(&buf);
 200        if (opts->gpg_sign)
 201                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 202        return buf.buf;
 203}
 204
 205int sequencer_remove_state(struct replay_opts *opts)
 206{
 207        struct strbuf buf = STRBUF_INIT;
 208        int i;
 209
 210        if (strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
 211                char *p = buf.buf;
 212                while (*p) {
 213                        char *eol = strchr(p, '\n');
 214                        if (eol)
 215                                *eol = '\0';
 216                        if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
 217                                warning(_("could not delete '%s'"), p);
 218                        if (!eol)
 219                                break;
 220                        p = eol + 1;
 221                }
 222        }
 223
 224        free(opts->gpg_sign);
 225        free(opts->strategy);
 226        for (i = 0; i < opts->xopts_nr; i++)
 227                free(opts->xopts[i]);
 228        free(opts->xopts);
 229
 230        strbuf_reset(&buf);
 231        strbuf_addstr(&buf, get_dir(opts));
 232        remove_dir_recursively(&buf, 0);
 233        strbuf_release(&buf);
 234
 235        return 0;
 236}
 237
 238static const char *action_name(const struct replay_opts *opts)
 239{
 240        switch (opts->action) {
 241        case REPLAY_REVERT:
 242                return N_("revert");
 243        case REPLAY_PICK:
 244                return N_("cherry-pick");
 245        case REPLAY_INTERACTIVE_REBASE:
 246                return N_("rebase -i");
 247        }
 248        die(_("Unknown action: %d"), opts->action);
 249}
 250
 251struct commit_message {
 252        char *parent_label;
 253        char *label;
 254        char *subject;
 255        const char *message;
 256};
 257
 258static const char *short_commit_name(struct commit *commit)
 259{
 260        return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 261}
 262
 263static int get_message(struct commit *commit, struct commit_message *out)
 264{
 265        const char *abbrev, *subject;
 266        int subject_len;
 267
 268        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 269        abbrev = short_commit_name(commit);
 270
 271        subject_len = find_commit_subject(out->message, &subject);
 272
 273        out->subject = xmemdupz(subject, subject_len);
 274        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 275        out->parent_label = xstrfmt("parent of %s", out->label);
 276
 277        return 0;
 278}
 279
 280static void free_message(struct commit *commit, struct commit_message *msg)
 281{
 282        free(msg->parent_label);
 283        free(msg->label);
 284        free(msg->subject);
 285        unuse_commit_buffer(commit, msg->message);
 286}
 287
 288static void print_advice(int show_hint, struct replay_opts *opts)
 289{
 290        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 291
 292        if (msg) {
 293                fprintf(stderr, "%s\n", msg);
 294                /*
 295                 * A conflict has occurred but the porcelain
 296                 * (typically rebase --interactive) wants to take care
 297                 * of the commit itself so remove CHERRY_PICK_HEAD
 298                 */
 299                unlink(git_path_cherry_pick_head());
 300                return;
 301        }
 302
 303        if (show_hint) {
 304                if (opts->no_commit)
 305                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 306                                 "with 'git add <paths>' or 'git rm <paths>'"));
 307                else
 308                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 309                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 310                                 "and commit the result with 'git commit'"));
 311        }
 312}
 313
 314static int write_message(const void *buf, size_t len, const char *filename,
 315                         int append_eol)
 316{
 317        static struct lock_file msg_file;
 318
 319        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 320        if (msg_fd < 0)
 321                return error_errno(_("could not lock '%s'"), filename);
 322        if (write_in_full(msg_fd, buf, len) < 0) {
 323                error_errno(_("could not write to '%s'"), filename);
 324                rollback_lock_file(&msg_file);
 325                return -1;
 326        }
 327        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 328                error_errno(_("could not write eol to '%s'"), filename);
 329                rollback_lock_file(&msg_file);
 330                return -1;
 331        }
 332        if (commit_lock_file(&msg_file) < 0) {
 333                rollback_lock_file(&msg_file);
 334                return error(_("failed to finalize '%s'."), filename);
 335        }
 336
 337        return 0;
 338}
 339
 340/*
 341 * Reads a file that was presumably written by a shell script, i.e. with an
 342 * end-of-line marker that needs to be stripped.
 343 *
 344 * Note that only the last end-of-line marker is stripped, consistent with the
 345 * behavior of "$(cat path)" in a shell script.
 346 *
 347 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 348 */
 349static int read_oneliner(struct strbuf *buf,
 350        const char *path, int skip_if_empty)
 351{
 352        int orig_len = buf->len;
 353
 354        if (!file_exists(path))
 355                return 0;
 356
 357        if (strbuf_read_file(buf, path, 0) < 0) {
 358                warning_errno(_("could not read '%s'"), path);
 359                return 0;
 360        }
 361
 362        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 363                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 364                        --buf->len;
 365                buf->buf[buf->len] = '\0';
 366        }
 367
 368        if (skip_if_empty && buf->len == orig_len)
 369                return 0;
 370
 371        return 1;
 372}
 373
 374static struct tree *empty_tree(void)
 375{
 376        return lookup_tree(the_hash_algo->empty_tree);
 377}
 378
 379static int error_dirty_index(struct replay_opts *opts)
 380{
 381        if (read_cache_unmerged())
 382                return error_resolve_conflict(_(action_name(opts)));
 383
 384        error(_("your local changes would be overwritten by %s."),
 385                _(action_name(opts)));
 386
 387        if (advice_commit_before_merge)
 388                advise(_("commit your changes or stash them to proceed."));
 389        return -1;
 390}
 391
 392static void update_abort_safety_file(void)
 393{
 394        struct object_id head;
 395
 396        /* Do nothing on a single-pick */
 397        if (!file_exists(git_path_seq_dir()))
 398                return;
 399
 400        if (!get_oid("HEAD", &head))
 401                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 402        else
 403                write_file(git_path_abort_safety_file(), "%s", "");
 404}
 405
 406static int fast_forward_to(const struct object_id *to, const struct object_id *from,
 407                        int unborn, struct replay_opts *opts)
 408{
 409        struct ref_transaction *transaction;
 410        struct strbuf sb = STRBUF_INIT;
 411        struct strbuf err = STRBUF_INIT;
 412
 413        read_cache();
 414        if (checkout_fast_forward(from, to, 1))
 415                return -1; /* the callee should have complained already */
 416
 417        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 418
 419        transaction = ref_transaction_begin(&err);
 420        if (!transaction ||
 421            ref_transaction_update(transaction, "HEAD",
 422                                   to, unborn ? &null_oid : from,
 423                                   0, sb.buf, &err) ||
 424            ref_transaction_commit(transaction, &err)) {
 425                ref_transaction_free(transaction);
 426                error("%s", err.buf);
 427                strbuf_release(&sb);
 428                strbuf_release(&err);
 429                return -1;
 430        }
 431
 432        strbuf_release(&sb);
 433        strbuf_release(&err);
 434        ref_transaction_free(transaction);
 435        update_abort_safety_file();
 436        return 0;
 437}
 438
 439void append_conflicts_hint(struct strbuf *msgbuf)
 440{
 441        int i;
 442
 443        strbuf_addch(msgbuf, '\n');
 444        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 445        for (i = 0; i < active_nr;) {
 446                const struct cache_entry *ce = active_cache[i++];
 447                if (ce_stage(ce)) {
 448                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 449                        while (i < active_nr && !strcmp(ce->name,
 450                                                        active_cache[i]->name))
 451                                i++;
 452                }
 453        }
 454}
 455
 456static int do_recursive_merge(struct commit *base, struct commit *next,
 457                              const char *base_label, const char *next_label,
 458                              struct object_id *head, struct strbuf *msgbuf,
 459                              struct replay_opts *opts)
 460{
 461        struct merge_options o;
 462        struct tree *result, *next_tree, *base_tree, *head_tree;
 463        int clean;
 464        char **xopt;
 465        static struct lock_file index_lock;
 466
 467        if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
 468                return -1;
 469
 470        read_cache();
 471
 472        init_merge_options(&o);
 473        o.ancestor = base ? base_label : "(empty tree)";
 474        o.branch1 = "HEAD";
 475        o.branch2 = next ? next_label : "(empty tree)";
 476        if (is_rebase_i(opts))
 477                o.buffer_output = 2;
 478        o.show_rename_progress = 1;
 479
 480        head_tree = parse_tree_indirect(head);
 481        next_tree = next ? next->tree : empty_tree();
 482        base_tree = base ? base->tree : empty_tree();
 483
 484        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 485                parse_merge_opt(&o, *xopt);
 486
 487        clean = merge_trees(&o,
 488                            head_tree,
 489                            next_tree, base_tree, &result);
 490        if (is_rebase_i(opts) && clean <= 0)
 491                fputs(o.obuf.buf, stdout);
 492        strbuf_release(&o.obuf);
 493        diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
 494        if (clean < 0)
 495                return clean;
 496
 497        if (active_cache_changed &&
 498            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 499                /*
 500                 * TRANSLATORS: %s will be "revert", "cherry-pick" or
 501                 * "rebase -i".
 502                 */
 503                return error(_("%s: Unable to write new index file"),
 504                        _(action_name(opts)));
 505        rollback_lock_file(&index_lock);
 506
 507        if (opts->signoff)
 508                append_signoff(msgbuf, 0, 0);
 509
 510        if (!clean)
 511                append_conflicts_hint(msgbuf);
 512
 513        return !clean;
 514}
 515
 516static int is_index_unchanged(void)
 517{
 518        struct object_id head_oid;
 519        struct commit *head_commit;
 520
 521        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
 522                return error(_("could not resolve HEAD commit"));
 523
 524        head_commit = lookup_commit(&head_oid);
 525
 526        /*
 527         * If head_commit is NULL, check_commit, called from
 528         * lookup_commit, would have indicated that head_commit is not
 529         * a commit object already.  parse_commit() will return failure
 530         * without further complaints in such a case.  Otherwise, if
 531         * the commit is invalid, parse_commit() will complain.  So
 532         * there is nothing for us to say here.  Just return failure.
 533         */
 534        if (parse_commit(head_commit))
 535                return -1;
 536
 537        if (!active_cache_tree)
 538                active_cache_tree = cache_tree();
 539
 540        if (!cache_tree_fully_valid(active_cache_tree))
 541                if (cache_tree_update(&the_index, 0))
 542                        return error(_("unable to update cache tree"));
 543
 544        return !oidcmp(&active_cache_tree->oid,
 545                       &head_commit->tree->object.oid);
 546}
 547
 548static int write_author_script(const char *message)
 549{
 550        struct strbuf buf = STRBUF_INIT;
 551        const char *eol;
 552        int res;
 553
 554        for (;;)
 555                if (!*message || starts_with(message, "\n")) {
 556missing_author:
 557                        /* Missing 'author' line? */
 558                        unlink(rebase_path_author_script());
 559                        return 0;
 560                } else if (skip_prefix(message, "author ", &message))
 561                        break;
 562                else if ((eol = strchr(message, '\n')))
 563                        message = eol + 1;
 564                else
 565                        goto missing_author;
 566
 567        strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
 568        while (*message && *message != '\n' && *message != '\r')
 569                if (skip_prefix(message, " <", &message))
 570                        break;
 571                else if (*message != '\'')
 572                        strbuf_addch(&buf, *(message++));
 573                else
 574                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 575        strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
 576        while (*message && *message != '\n' && *message != '\r')
 577                if (skip_prefix(message, "> ", &message))
 578                        break;
 579                else if (*message != '\'')
 580                        strbuf_addch(&buf, *(message++));
 581                else
 582                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 583        strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
 584        while (*message && *message != '\n' && *message != '\r')
 585                if (*message != '\'')
 586                        strbuf_addch(&buf, *(message++));
 587                else
 588                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 589        res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
 590        strbuf_release(&buf);
 591        return res;
 592}
 593
 594/*
 595 * Read a list of environment variable assignments (such as the author-script
 596 * file) into an environment block. Returns -1 on error, 0 otherwise.
 597 */
 598static int read_env_script(struct argv_array *env)
 599{
 600        struct strbuf script = STRBUF_INIT;
 601        int i, count = 0;
 602        char *p, *p2;
 603
 604        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 605                return -1;
 606
 607        for (p = script.buf; *p; p++)
 608                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 609                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 610                else if (*p == '\'')
 611                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 612                else if (*p == '\n') {
 613                        *p = '\0';
 614                        count++;
 615                }
 616
 617        for (i = 0, p = script.buf; i < count; i++) {
 618                argv_array_push(env, p);
 619                p += strlen(p) + 1;
 620        }
 621
 622        return 0;
 623}
 624
 625static const char staged_changes_advice[] =
 626N_("you have staged changes in your working tree\n"
 627"If these changes are meant to be squashed into the previous commit, run:\n"
 628"\n"
 629"  git commit --amend %s\n"
 630"\n"
 631"If they are meant to go into a new commit, run:\n"
 632"\n"
 633"  git commit %s\n"
 634"\n"
 635"In both cases, once you're done, continue with:\n"
 636"\n"
 637"  git rebase --continue\n");
 638
 639#define ALLOW_EMPTY (1<<0)
 640#define EDIT_MSG    (1<<1)
 641#define AMEND_MSG   (1<<2)
 642#define CLEANUP_MSG (1<<3)
 643#define VERIFY_MSG  (1<<4)
 644
 645/*
 646 * If we are cherry-pick, and if the merge did not result in
 647 * hand-editing, we will hit this commit and inherit the original
 648 * author date and name.
 649 *
 650 * If we are revert, or if our cherry-pick results in a hand merge,
 651 * we had better say that the current user is responsible for that.
 652 *
 653 * An exception is when run_git_commit() is called during an
 654 * interactive rebase: in that case, we will want to retain the
 655 * author metadata.
 656 */
 657static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 658                          unsigned int flags)
 659{
 660        struct child_process cmd = CHILD_PROCESS_INIT;
 661        const char *value;
 662
 663        cmd.git_cmd = 1;
 664
 665        if (is_rebase_i(opts)) {
 666                if (!(flags & EDIT_MSG)) {
 667                        cmd.stdout_to_stderr = 1;
 668                        cmd.err = -1;
 669                }
 670
 671                if (read_env_script(&cmd.env_array)) {
 672                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 673
 674                        return error(_(staged_changes_advice),
 675                                     gpg_opt, gpg_opt);
 676                }
 677        }
 678
 679        argv_array_push(&cmd.args, "commit");
 680
 681        if (!(flags & VERIFY_MSG))
 682                argv_array_push(&cmd.args, "-n");
 683        if ((flags & AMEND_MSG))
 684                argv_array_push(&cmd.args, "--amend");
 685        if (opts->gpg_sign)
 686                argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
 687        if (opts->signoff)
 688                argv_array_push(&cmd.args, "-s");
 689        if (defmsg)
 690                argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
 691        if ((flags & CLEANUP_MSG))
 692                argv_array_push(&cmd.args, "--cleanup=strip");
 693        if ((flags & EDIT_MSG))
 694                argv_array_push(&cmd.args, "-e");
 695        else if (!(flags & CLEANUP_MSG) &&
 696                 !opts->signoff && !opts->record_origin &&
 697                 git_config_get_value("commit.cleanup", &value))
 698                argv_array_push(&cmd.args, "--cleanup=verbatim");
 699
 700        if ((flags & ALLOW_EMPTY))
 701                argv_array_push(&cmd.args, "--allow-empty");
 702
 703        if (opts->allow_empty_message)
 704                argv_array_push(&cmd.args, "--allow-empty-message");
 705
 706        if (cmd.err == -1) {
 707                /* hide stderr on success */
 708                struct strbuf buf = STRBUF_INIT;
 709                int rc = pipe_command(&cmd,
 710                                      NULL, 0,
 711                                      /* stdout is already redirected */
 712                                      NULL, 0,
 713                                      &buf, 0);
 714                if (rc)
 715                        fputs(buf.buf, stderr);
 716                strbuf_release(&buf);
 717                return rc;
 718        }
 719
 720        return run_command(&cmd);
 721}
 722
 723static int is_original_commit_empty(struct commit *commit)
 724{
 725        const struct object_id *ptree_oid;
 726
 727        if (parse_commit(commit))
 728                return error(_("could not parse commit %s"),
 729                             oid_to_hex(&commit->object.oid));
 730        if (commit->parents) {
 731                struct commit *parent = commit->parents->item;
 732                if (parse_commit(parent))
 733                        return error(_("could not parse parent commit %s"),
 734                                oid_to_hex(&parent->object.oid));
 735                ptree_oid = &parent->tree->object.oid;
 736        } else {
 737                ptree_oid = the_hash_algo->empty_tree; /* commit is root */
 738        }
 739
 740        return !oidcmp(ptree_oid, &commit->tree->object.oid);
 741}
 742
 743/*
 744 * Do we run "git commit" with "--allow-empty"?
 745 */
 746static int allow_empty(struct replay_opts *opts, struct commit *commit)
 747{
 748        int index_unchanged, empty_commit;
 749
 750        /*
 751         * Three cases:
 752         *
 753         * (1) we do not allow empty at all and error out.
 754         *
 755         * (2) we allow ones that were initially empty, but
 756         * forbid the ones that become empty;
 757         *
 758         * (3) we allow both.
 759         */
 760        if (!opts->allow_empty)
 761                return 0; /* let "git commit" barf as necessary */
 762
 763        index_unchanged = is_index_unchanged();
 764        if (index_unchanged < 0)
 765                return index_unchanged;
 766        if (!index_unchanged)
 767                return 0; /* we do not have to say --allow-empty */
 768
 769        if (opts->keep_redundant_commits)
 770                return 1;
 771
 772        empty_commit = is_original_commit_empty(commit);
 773        if (empty_commit < 0)
 774                return empty_commit;
 775        if (!empty_commit)
 776                return 0;
 777        else
 778                return 1;
 779}
 780
 781/*
 782 * Note that ordering matters in this enum. Not only must it match the mapping
 783 * below, it is also divided into several sections that matter.  When adding
 784 * new commands, make sure you add it in the right section.
 785 */
 786enum todo_command {
 787        /* commands that handle commits */
 788        TODO_PICK = 0,
 789        TODO_REVERT,
 790        TODO_EDIT,
 791        TODO_REWORD,
 792        TODO_FIXUP,
 793        TODO_SQUASH,
 794        /* commands that do something else than handling a single commit */
 795        TODO_EXEC,
 796        TODO_LABEL,
 797        TODO_RESET,
 798        TODO_MERGE,
 799        TODO_MERGE_AND_EDIT,
 800        /* commands that do nothing but are counted for reporting progress */
 801        TODO_NOOP,
 802        TODO_DROP,
 803        /* comments (not counted for reporting progress) */
 804        TODO_COMMENT
 805};
 806
 807static struct {
 808        char c;
 809        const char *str;
 810} todo_command_info[] = {
 811        { 'p', "pick" },
 812        { 0,   "revert" },
 813        { 'e', "edit" },
 814        { 'r', "reword" },
 815        { 'f', "fixup" },
 816        { 's', "squash" },
 817        { 'x', "exec" },
 818        { 'l', "label" },
 819        { 't', "reset" },
 820        { 'm', "merge" },
 821        { 0, "merge" }, /* MERGE_AND_EDIT */
 822        { 0,   "noop" },
 823        { 'd', "drop" },
 824        { 0,   NULL }
 825};
 826
 827static const char *command_to_string(const enum todo_command command)
 828{
 829        if (command < TODO_COMMENT)
 830                return todo_command_info[command].str;
 831        die("Unknown command: %d", command);
 832}
 833
 834static char command_to_char(const enum todo_command command)
 835{
 836        if (command < TODO_COMMENT && todo_command_info[command].c)
 837                return todo_command_info[command].c;
 838        return comment_line_char;
 839}
 840
 841static int is_noop(const enum todo_command command)
 842{
 843        return TODO_NOOP <= command;
 844}
 845
 846static int is_fixup(enum todo_command command)
 847{
 848        return command == TODO_FIXUP || command == TODO_SQUASH;
 849}
 850
 851static int update_squash_messages(enum todo_command command,
 852                struct commit *commit, struct replay_opts *opts)
 853{
 854        struct strbuf buf = STRBUF_INIT;
 855        int count, res;
 856        const char *message, *body;
 857
 858        if (file_exists(rebase_path_squash_msg())) {
 859                struct strbuf header = STRBUF_INIT;
 860                char *eol, *p;
 861
 862                if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
 863                        return error(_("could not read '%s'"),
 864                                rebase_path_squash_msg());
 865
 866                p = buf.buf + 1;
 867                eol = strchrnul(buf.buf, '\n');
 868                if (buf.buf[0] != comment_line_char ||
 869                    (p += strcspn(p, "0123456789\n")) == eol)
 870                        return error(_("unexpected 1st line of squash message:"
 871                                       "\n\n\t%.*s"),
 872                                     (int)(eol - buf.buf), buf.buf);
 873                count = strtol(p, NULL, 10);
 874
 875                if (count < 1)
 876                        return error(_("invalid 1st line of squash message:\n"
 877                                       "\n\t%.*s"),
 878                                     (int)(eol - buf.buf), buf.buf);
 879
 880                strbuf_addf(&header, "%c ", comment_line_char);
 881                strbuf_addf(&header,
 882                            _("This is a combination of %d commits."), ++count);
 883                strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
 884                strbuf_release(&header);
 885        } else {
 886                struct object_id head;
 887                struct commit *head_commit;
 888                const char *head_message, *body;
 889
 890                if (get_oid("HEAD", &head))
 891                        return error(_("need a HEAD to fixup"));
 892                if (!(head_commit = lookup_commit_reference(&head)))
 893                        return error(_("could not read HEAD"));
 894                if (!(head_message = get_commit_buffer(head_commit, NULL)))
 895                        return error(_("could not read HEAD's commit message"));
 896
 897                find_commit_subject(head_message, &body);
 898                if (write_message(body, strlen(body),
 899                                  rebase_path_fixup_msg(), 0)) {
 900                        unuse_commit_buffer(head_commit, head_message);
 901                        return error(_("cannot write '%s'"),
 902                                     rebase_path_fixup_msg());
 903                }
 904
 905                count = 2;
 906                strbuf_addf(&buf, "%c ", comment_line_char);
 907                strbuf_addf(&buf, _("This is a combination of %d commits."),
 908                            count);
 909                strbuf_addf(&buf, "\n%c ", comment_line_char);
 910                strbuf_addstr(&buf, _("This is the 1st commit message:"));
 911                strbuf_addstr(&buf, "\n\n");
 912                strbuf_addstr(&buf, body);
 913
 914                unuse_commit_buffer(head_commit, head_message);
 915        }
 916
 917        if (!(message = get_commit_buffer(commit, NULL)))
 918                return error(_("could not read commit message of %s"),
 919                             oid_to_hex(&commit->object.oid));
 920        find_commit_subject(message, &body);
 921
 922        if (command == TODO_SQUASH) {
 923                unlink(rebase_path_fixup_msg());
 924                strbuf_addf(&buf, "\n%c ", comment_line_char);
 925                strbuf_addf(&buf, _("This is the commit message #%d:"), count);
 926                strbuf_addstr(&buf, "\n\n");
 927                strbuf_addstr(&buf, body);
 928        } else if (command == TODO_FIXUP) {
 929                strbuf_addf(&buf, "\n%c ", comment_line_char);
 930                strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
 931                            count);
 932                strbuf_addstr(&buf, "\n\n");
 933                strbuf_add_commented_lines(&buf, body, strlen(body));
 934        } else
 935                return error(_("unknown command: %d"), command);
 936        unuse_commit_buffer(commit, message);
 937
 938        res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
 939        strbuf_release(&buf);
 940        return res;
 941}
 942
 943static void flush_rewritten_pending(void) {
 944        struct strbuf buf = STRBUF_INIT;
 945        struct object_id newoid;
 946        FILE *out;
 947
 948        if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
 949            !get_oid("HEAD", &newoid) &&
 950            (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
 951                char *bol = buf.buf, *eol;
 952
 953                while (*bol) {
 954                        eol = strchrnul(bol, '\n');
 955                        fprintf(out, "%.*s %s\n", (int)(eol - bol),
 956                                        bol, oid_to_hex(&newoid));
 957                        if (!*eol)
 958                                break;
 959                        bol = eol + 1;
 960                }
 961                fclose(out);
 962                unlink(rebase_path_rewritten_pending());
 963        }
 964        strbuf_release(&buf);
 965}
 966
 967static void record_in_rewritten(struct object_id *oid,
 968                enum todo_command next_command) {
 969        FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
 970
 971        if (!out)
 972                return;
 973
 974        fprintf(out, "%s\n", oid_to_hex(oid));
 975        fclose(out);
 976
 977        if (!is_fixup(next_command))
 978                flush_rewritten_pending();
 979}
 980
 981static int do_pick_commit(enum todo_command command, struct commit *commit,
 982                struct replay_opts *opts, int final_fixup)
 983{
 984        unsigned int flags = opts->edit ? EDIT_MSG : 0;
 985        const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
 986        struct object_id head;
 987        struct commit *base, *next, *parent;
 988        const char *base_label, *next_label;
 989        struct commit_message msg = { NULL, NULL, NULL, NULL };
 990        struct strbuf msgbuf = STRBUF_INIT;
 991        int res, unborn = 0, allow;
 992
 993        if (opts->no_commit) {
 994                /*
 995                 * We do not intend to commit immediately.  We just want to
 996                 * merge the differences in, so let's compute the tree
 997                 * that represents the "current" state for merge-recursive
 998                 * to work on.
 999                 */
1000                if (write_cache_as_tree(head.hash, 0, NULL))
1001                        return error(_("your index file is unmerged."));
1002        } else {
1003                unborn = get_oid("HEAD", &head);
1004                if (unborn)
1005                        oidcpy(&head, the_hash_algo->empty_tree);
1006                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1007                                       NULL, 0))
1008                        return error_dirty_index(opts);
1009        }
1010        discard_cache();
1011
1012        if (!commit->parents)
1013                parent = NULL;
1014        else if (commit->parents->next) {
1015                /* Reverting or cherry-picking a merge commit */
1016                int cnt;
1017                struct commit_list *p;
1018
1019                if (!opts->mainline)
1020                        return error(_("commit %s is a merge but no -m option was given."),
1021                                oid_to_hex(&commit->object.oid));
1022
1023                for (cnt = 1, p = commit->parents;
1024                     cnt != opts->mainline && p;
1025                     cnt++)
1026                        p = p->next;
1027                if (cnt != opts->mainline || !p)
1028                        return error(_("commit %s does not have parent %d"),
1029                                oid_to_hex(&commit->object.oid), opts->mainline);
1030                parent = p->item;
1031        } else if (0 < opts->mainline)
1032                return error(_("mainline was specified but commit %s is not a merge."),
1033                        oid_to_hex(&commit->object.oid));
1034        else
1035                parent = commit->parents->item;
1036
1037        if (get_message(commit, &msg) != 0)
1038                return error(_("cannot get commit message for %s"),
1039                        oid_to_hex(&commit->object.oid));
1040
1041        if (opts->allow_ff && !is_fixup(command) &&
1042            ((parent && !oidcmp(&parent->object.oid, &head)) ||
1043             (!parent && unborn))) {
1044                if (is_rebase_i(opts))
1045                        write_author_script(msg.message);
1046                res = fast_forward_to(&commit->object.oid, &head, unborn,
1047                        opts);
1048                if (res || command != TODO_REWORD)
1049                        goto leave;
1050                flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1051                msg_file = NULL;
1052                goto fast_forward_edit;
1053        }
1054        if (parent && parse_commit(parent) < 0)
1055                /* TRANSLATORS: The first %s will be a "todo" command like
1056                   "revert" or "pick", the second %s a SHA1. */
1057                return error(_("%s: cannot parse parent commit %s"),
1058                        command_to_string(command),
1059                        oid_to_hex(&parent->object.oid));
1060
1061        /*
1062         * "commit" is an existing commit.  We would want to apply
1063         * the difference it introduces since its first parent "prev"
1064         * on top of the current HEAD if we are cherry-pick.  Or the
1065         * reverse of it if we are revert.
1066         */
1067
1068        if (command == TODO_REVERT) {
1069                base = commit;
1070                base_label = msg.label;
1071                next = parent;
1072                next_label = msg.parent_label;
1073                strbuf_addstr(&msgbuf, "Revert \"");
1074                strbuf_addstr(&msgbuf, msg.subject);
1075                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1076                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1077
1078                if (commit->parents && commit->parents->next) {
1079                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1080                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1081                }
1082                strbuf_addstr(&msgbuf, ".\n");
1083        } else {
1084                const char *p;
1085
1086                base = parent;
1087                base_label = msg.parent_label;
1088                next = commit;
1089                next_label = msg.label;
1090
1091                /* Append the commit log message to msgbuf. */
1092                if (find_commit_subject(msg.message, &p))
1093                        strbuf_addstr(&msgbuf, p);
1094
1095                if (opts->record_origin) {
1096                        strbuf_complete_line(&msgbuf);
1097                        if (!has_conforming_footer(&msgbuf, NULL, 0))
1098                                strbuf_addch(&msgbuf, '\n');
1099                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
1100                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1101                        strbuf_addstr(&msgbuf, ")\n");
1102                }
1103        }
1104
1105        if (command == TODO_REWORD)
1106                flags |= EDIT_MSG | VERIFY_MSG;
1107        else if (is_fixup(command)) {
1108                if (update_squash_messages(command, commit, opts))
1109                        return -1;
1110                flags |= AMEND_MSG;
1111                if (!final_fixup)
1112                        msg_file = rebase_path_squash_msg();
1113                else if (file_exists(rebase_path_fixup_msg())) {
1114                        flags |= CLEANUP_MSG;
1115                        msg_file = rebase_path_fixup_msg();
1116                } else {
1117                        const char *dest = git_path_squash_msg();
1118                        unlink(dest);
1119                        if (copy_file(dest, rebase_path_squash_msg(), 0666))
1120                                return error(_("could not rename '%s' to '%s'"),
1121                                             rebase_path_squash_msg(), dest);
1122                        unlink(git_path_merge_msg());
1123                        msg_file = dest;
1124                        flags |= EDIT_MSG;
1125                }
1126        }
1127
1128        if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1129                res = -1;
1130        else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1131                res = do_recursive_merge(base, next, base_label, next_label,
1132                                         &head, &msgbuf, opts);
1133                if (res < 0)
1134                        return res;
1135                res |= write_message(msgbuf.buf, msgbuf.len,
1136                                     git_path_merge_msg(), 0);
1137        } else {
1138                struct commit_list *common = NULL;
1139                struct commit_list *remotes = NULL;
1140
1141                res = write_message(msgbuf.buf, msgbuf.len,
1142                                    git_path_merge_msg(), 0);
1143
1144                commit_list_insert(base, &common);
1145                commit_list_insert(next, &remotes);
1146                res |= try_merge_command(opts->strategy,
1147                                         opts->xopts_nr, (const char **)opts->xopts,
1148                                        common, oid_to_hex(&head), remotes);
1149                free_commit_list(common);
1150                free_commit_list(remotes);
1151        }
1152        strbuf_release(&msgbuf);
1153
1154        /*
1155         * If the merge was clean or if it failed due to conflict, we write
1156         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1157         * However, if the merge did not even start, then we don't want to
1158         * write it at all.
1159         */
1160        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1161            update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1162                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1163                res = -1;
1164        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1165            update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1166                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1167                res = -1;
1168
1169        if (res) {
1170                error(command == TODO_REVERT
1171                      ? _("could not revert %s... %s")
1172                      : _("could not apply %s... %s"),
1173                      short_commit_name(commit), msg.subject);
1174                print_advice(res == 1, opts);
1175                rerere(opts->allow_rerere_auto);
1176                goto leave;
1177        }
1178
1179        allow = allow_empty(opts, commit);
1180        if (allow < 0) {
1181                res = allow;
1182                goto leave;
1183        } else if (allow)
1184                flags |= ALLOW_EMPTY;
1185        if (!opts->no_commit)
1186fast_forward_edit:
1187                res = run_git_commit(msg_file, opts, flags);
1188
1189        if (!res && final_fixup) {
1190                unlink(rebase_path_fixup_msg());
1191                unlink(rebase_path_squash_msg());
1192        }
1193
1194leave:
1195        free_message(commit, &msg);
1196        update_abort_safety_file();
1197
1198        return res;
1199}
1200
1201static int prepare_revs(struct replay_opts *opts)
1202{
1203        /*
1204         * picking (but not reverting) ranges (but not individual revisions)
1205         * should be done in reverse
1206         */
1207        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1208                opts->revs->reverse ^= 1;
1209
1210        if (prepare_revision_walk(opts->revs))
1211                return error(_("revision walk setup failed"));
1212
1213        if (!opts->revs->commits)
1214                return error(_("empty commit set passed"));
1215        return 0;
1216}
1217
1218static int read_and_refresh_cache(struct replay_opts *opts)
1219{
1220        static struct lock_file index_lock;
1221        int index_fd = hold_locked_index(&index_lock, 0);
1222        if (read_index_preload(&the_index, NULL) < 0) {
1223                rollback_lock_file(&index_lock);
1224                return error(_("git %s: failed to read the index"),
1225                        _(action_name(opts)));
1226        }
1227        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1228        if (the_index.cache_changed && index_fd >= 0) {
1229                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1230                        return error(_("git %s: failed to refresh the index"),
1231                                _(action_name(opts)));
1232                }
1233        }
1234        rollback_lock_file(&index_lock);
1235        return 0;
1236}
1237
1238struct todo_item {
1239        enum todo_command command;
1240        struct commit *commit;
1241        const char *arg;
1242        int arg_len;
1243        size_t offset_in_buf;
1244};
1245
1246struct todo_list {
1247        struct strbuf buf;
1248        struct todo_item *items;
1249        int nr, alloc, current;
1250        int done_nr, total_nr;
1251        struct stat_data stat;
1252};
1253
1254#define TODO_LIST_INIT { STRBUF_INIT }
1255
1256static void todo_list_release(struct todo_list *todo_list)
1257{
1258        strbuf_release(&todo_list->buf);
1259        FREE_AND_NULL(todo_list->items);
1260        todo_list->nr = todo_list->alloc = 0;
1261}
1262
1263static struct todo_item *append_new_todo(struct todo_list *todo_list)
1264{
1265        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1266        return todo_list->items + todo_list->nr++;
1267}
1268
1269static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1270{
1271        struct object_id commit_oid;
1272        char *end_of_object_name;
1273        int i, saved, status, padding;
1274
1275        /* left-trim */
1276        bol += strspn(bol, " \t");
1277
1278        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1279                item->command = TODO_COMMENT;
1280                item->commit = NULL;
1281                item->arg = bol;
1282                item->arg_len = eol - bol;
1283                return 0;
1284        }
1285
1286        for (i = 0; i < TODO_COMMENT; i++)
1287                if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1288                        item->command = i;
1289                        break;
1290                } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1291                        bol++;
1292                        item->command = i;
1293                        break;
1294                }
1295        if (i >= TODO_COMMENT)
1296                return -1;
1297
1298        /* Eat up extra spaces/ tabs before object name */
1299        padding = strspn(bol, " \t");
1300        bol += padding;
1301
1302        if (item->command == TODO_NOOP) {
1303                if (bol != eol)
1304                        return error(_("%s does not accept arguments: '%s'"),
1305                                     command_to_string(item->command), bol);
1306                item->commit = NULL;
1307                item->arg = bol;
1308                item->arg_len = eol - bol;
1309                return 0;
1310        }
1311
1312        if (!padding)
1313                return error(_("missing arguments for %s"),
1314                             command_to_string(item->command));
1315
1316        if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1317            item->command == TODO_RESET) {
1318                item->commit = NULL;
1319                item->arg = bol;
1320                item->arg_len = (int)(eol - bol);
1321                return 0;
1322        }
1323
1324        if (item->command == TODO_MERGE) {
1325                if (skip_prefix(bol, "-C", &bol))
1326                        bol += strspn(bol, " \t");
1327                else if (skip_prefix(bol, "-c", &bol)) {
1328                        bol += strspn(bol, " \t");
1329                        item->command = TODO_MERGE_AND_EDIT;
1330                } else {
1331                        item->command = TODO_MERGE_AND_EDIT;
1332                        item->commit = NULL;
1333                        item->arg = bol;
1334                        item->arg_len = (int)(eol - bol);
1335                        return 0;
1336                }
1337        }
1338
1339        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1340        saved = *end_of_object_name;
1341        *end_of_object_name = '\0';
1342        status = get_oid(bol, &commit_oid);
1343        *end_of_object_name = saved;
1344
1345        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1346        item->arg_len = (int)(eol - item->arg);
1347
1348        if (status < 0)
1349                return -1;
1350
1351        item->commit = lookup_commit_reference(&commit_oid);
1352        return !item->commit;
1353}
1354
1355static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1356{
1357        struct todo_item *item;
1358        char *p = buf, *next_p;
1359        int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1360
1361        for (i = 1; *p; i++, p = next_p) {
1362                char *eol = strchrnul(p, '\n');
1363
1364                next_p = *eol ? eol + 1 /* skip LF */ : eol;
1365
1366                if (p != eol && eol[-1] == '\r')
1367                        eol--; /* strip Carriage Return */
1368
1369                item = append_new_todo(todo_list);
1370                item->offset_in_buf = p - todo_list->buf.buf;
1371                if (parse_insn_line(item, p, eol)) {
1372                        res = error(_("invalid line %d: %.*s"),
1373                                i, (int)(eol - p), p);
1374                        item->command = TODO_NOOP;
1375                }
1376
1377                if (fixup_okay)
1378                        ; /* do nothing */
1379                else if (is_fixup(item->command))
1380                        return error(_("cannot '%s' without a previous commit"),
1381                                command_to_string(item->command));
1382                else if (!is_noop(item->command))
1383                        fixup_okay = 1;
1384        }
1385
1386        return res;
1387}
1388
1389static int count_commands(struct todo_list *todo_list)
1390{
1391        int count = 0, i;
1392
1393        for (i = 0; i < todo_list->nr; i++)
1394                if (todo_list->items[i].command != TODO_COMMENT)
1395                        count++;
1396
1397        return count;
1398}
1399
1400static int read_populate_todo(struct todo_list *todo_list,
1401                        struct replay_opts *opts)
1402{
1403        struct stat st;
1404        const char *todo_file = get_todo_path(opts);
1405        int fd, res;
1406
1407        strbuf_reset(&todo_list->buf);
1408        fd = open(todo_file, O_RDONLY);
1409        if (fd < 0)
1410                return error_errno(_("could not open '%s'"), todo_file);
1411        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1412                close(fd);
1413                return error(_("could not read '%s'."), todo_file);
1414        }
1415        close(fd);
1416
1417        res = stat(todo_file, &st);
1418        if (res)
1419                return error(_("could not stat '%s'"), todo_file);
1420        fill_stat_data(&todo_list->stat, &st);
1421
1422        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1423        if (res) {
1424                if (is_rebase_i(opts))
1425                        return error(_("please fix this using "
1426                                       "'git rebase --edit-todo'."));
1427                return error(_("unusable instruction sheet: '%s'"), todo_file);
1428        }
1429
1430        if (!todo_list->nr &&
1431            (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1432                return error(_("no commits parsed."));
1433
1434        if (!is_rebase_i(opts)) {
1435                enum todo_command valid =
1436                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1437                int i;
1438
1439                for (i = 0; i < todo_list->nr; i++)
1440                        if (valid == todo_list->items[i].command)
1441                                continue;
1442                        else if (valid == TODO_PICK)
1443                                return error(_("cannot cherry-pick during a revert."));
1444                        else
1445                                return error(_("cannot revert during a cherry-pick."));
1446        }
1447
1448        if (is_rebase_i(opts)) {
1449                struct todo_list done = TODO_LIST_INIT;
1450                FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1451
1452                if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1453                                !parse_insn_buffer(done.buf.buf, &done))
1454                        todo_list->done_nr = count_commands(&done);
1455                else
1456                        todo_list->done_nr = 0;
1457
1458                todo_list->total_nr = todo_list->done_nr
1459                        + count_commands(todo_list);
1460                todo_list_release(&done);
1461
1462                if (f) {
1463                        fprintf(f, "%d\n", todo_list->total_nr);
1464                        fclose(f);
1465                }
1466        }
1467
1468        return 0;
1469}
1470
1471static int git_config_string_dup(char **dest,
1472                                 const char *var, const char *value)
1473{
1474        if (!value)
1475                return config_error_nonbool(var);
1476        free(*dest);
1477        *dest = xstrdup(value);
1478        return 0;
1479}
1480
1481static int populate_opts_cb(const char *key, const char *value, void *data)
1482{
1483        struct replay_opts *opts = data;
1484        int error_flag = 1;
1485
1486        if (!value)
1487                error_flag = 0;
1488        else if (!strcmp(key, "options.no-commit"))
1489                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1490        else if (!strcmp(key, "options.edit"))
1491                opts->edit = git_config_bool_or_int(key, value, &error_flag);
1492        else if (!strcmp(key, "options.signoff"))
1493                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1494        else if (!strcmp(key, "options.record-origin"))
1495                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1496        else if (!strcmp(key, "options.allow-ff"))
1497                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1498        else if (!strcmp(key, "options.mainline"))
1499                opts->mainline = git_config_int(key, value);
1500        else if (!strcmp(key, "options.strategy"))
1501                git_config_string_dup(&opts->strategy, key, value);
1502        else if (!strcmp(key, "options.gpg-sign"))
1503                git_config_string_dup(&opts->gpg_sign, key, value);
1504        else if (!strcmp(key, "options.strategy-option")) {
1505                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1506                opts->xopts[opts->xopts_nr++] = xstrdup(value);
1507        } else if (!strcmp(key, "options.allow-rerere-auto"))
1508                opts->allow_rerere_auto =
1509                        git_config_bool_or_int(key, value, &error_flag) ?
1510                                RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1511        else
1512                return error(_("invalid key: %s"), key);
1513
1514        if (!error_flag)
1515                return error(_("invalid value for %s: %s"), key, value);
1516
1517        return 0;
1518}
1519
1520static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1521{
1522        int i;
1523
1524        strbuf_reset(buf);
1525        if (!read_oneliner(buf, rebase_path_strategy(), 0))
1526                return;
1527        opts->strategy = strbuf_detach(buf, NULL);
1528        if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1529                return;
1530
1531        opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1532        for (i = 0; i < opts->xopts_nr; i++) {
1533                const char *arg = opts->xopts[i];
1534
1535                skip_prefix(arg, "--", &arg);
1536                opts->xopts[i] = xstrdup(arg);
1537        }
1538}
1539
1540static int read_populate_opts(struct replay_opts *opts)
1541{
1542        if (is_rebase_i(opts)) {
1543                struct strbuf buf = STRBUF_INIT;
1544
1545                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1546                        if (!starts_with(buf.buf, "-S"))
1547                                strbuf_reset(&buf);
1548                        else {
1549                                free(opts->gpg_sign);
1550                                opts->gpg_sign = xstrdup(buf.buf + 2);
1551                        }
1552                        strbuf_reset(&buf);
1553                }
1554
1555                if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1556                        if (!strcmp(buf.buf, "--rerere-autoupdate"))
1557                                opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1558                        else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1559                                opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1560                        strbuf_reset(&buf);
1561                }
1562
1563                if (file_exists(rebase_path_verbose()))
1564                        opts->verbose = 1;
1565
1566                read_strategy_opts(opts, &buf);
1567                strbuf_release(&buf);
1568
1569                return 0;
1570        }
1571
1572        if (!file_exists(git_path_opts_file()))
1573                return 0;
1574        /*
1575         * The function git_parse_source(), called from git_config_from_file(),
1576         * may die() in case of a syntactically incorrect file. We do not care
1577         * about this case, though, because we wrote that file ourselves, so we
1578         * are pretty certain that it is syntactically correct.
1579         */
1580        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1581                return error(_("malformed options sheet: '%s'"),
1582                        git_path_opts_file());
1583        return 0;
1584}
1585
1586static int walk_revs_populate_todo(struct todo_list *todo_list,
1587                                struct replay_opts *opts)
1588{
1589        enum todo_command command = opts->action == REPLAY_PICK ?
1590                TODO_PICK : TODO_REVERT;
1591        const char *command_string = todo_command_info[command].str;
1592        struct commit *commit;
1593
1594        if (prepare_revs(opts))
1595                return -1;
1596
1597        while ((commit = get_revision(opts->revs))) {
1598                struct todo_item *item = append_new_todo(todo_list);
1599                const char *commit_buffer = get_commit_buffer(commit, NULL);
1600                const char *subject;
1601                int subject_len;
1602
1603                item->command = command;
1604                item->commit = commit;
1605                item->arg = NULL;
1606                item->arg_len = 0;
1607                item->offset_in_buf = todo_list->buf.len;
1608                subject_len = find_commit_subject(commit_buffer, &subject);
1609                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1610                        short_commit_name(commit), subject_len, subject);
1611                unuse_commit_buffer(commit, commit_buffer);
1612        }
1613        return 0;
1614}
1615
1616static int create_seq_dir(void)
1617{
1618        if (file_exists(git_path_seq_dir())) {
1619                error(_("a cherry-pick or revert is already in progress"));
1620                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1621                return -1;
1622        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1623                return error_errno(_("could not create sequencer directory '%s'"),
1624                                   git_path_seq_dir());
1625        return 0;
1626}
1627
1628static int save_head(const char *head)
1629{
1630        static struct lock_file head_lock;
1631        struct strbuf buf = STRBUF_INIT;
1632        int fd;
1633        ssize_t written;
1634
1635        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1636        if (fd < 0) {
1637                error_errno(_("could not lock HEAD"));
1638                rollback_lock_file(&head_lock);
1639                return -1;
1640        }
1641        strbuf_addf(&buf, "%s\n", head);
1642        written = write_in_full(fd, buf.buf, buf.len);
1643        strbuf_release(&buf);
1644        if (written < 0) {
1645                error_errno(_("could not write to '%s'"), git_path_head_file());
1646                rollback_lock_file(&head_lock);
1647                return -1;
1648        }
1649        if (commit_lock_file(&head_lock) < 0) {
1650                rollback_lock_file(&head_lock);
1651                return error(_("failed to finalize '%s'."), git_path_head_file());
1652        }
1653        return 0;
1654}
1655
1656static int rollback_is_safe(void)
1657{
1658        struct strbuf sb = STRBUF_INIT;
1659        struct object_id expected_head, actual_head;
1660
1661        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1662                strbuf_trim(&sb);
1663                if (get_oid_hex(sb.buf, &expected_head)) {
1664                        strbuf_release(&sb);
1665                        die(_("could not parse %s"), git_path_abort_safety_file());
1666                }
1667                strbuf_release(&sb);
1668        }
1669        else if (errno == ENOENT)
1670                oidclr(&expected_head);
1671        else
1672                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1673
1674        if (get_oid("HEAD", &actual_head))
1675                oidclr(&actual_head);
1676
1677        return !oidcmp(&actual_head, &expected_head);
1678}
1679
1680static int reset_for_rollback(const struct object_id *oid)
1681{
1682        const char *argv[4];    /* reset --merge <arg> + NULL */
1683
1684        argv[0] = "reset";
1685        argv[1] = "--merge";
1686        argv[2] = oid_to_hex(oid);
1687        argv[3] = NULL;
1688        return run_command_v_opt(argv, RUN_GIT_CMD);
1689}
1690
1691static int rollback_single_pick(void)
1692{
1693        struct object_id head_oid;
1694
1695        if (!file_exists(git_path_cherry_pick_head()) &&
1696            !file_exists(git_path_revert_head()))
1697                return error(_("no cherry-pick or revert in progress"));
1698        if (read_ref_full("HEAD", 0, &head_oid, NULL))
1699                return error(_("cannot resolve HEAD"));
1700        if (is_null_oid(&head_oid))
1701                return error(_("cannot abort from a branch yet to be born"));
1702        return reset_for_rollback(&head_oid);
1703}
1704
1705int sequencer_rollback(struct replay_opts *opts)
1706{
1707        FILE *f;
1708        struct object_id oid;
1709        struct strbuf buf = STRBUF_INIT;
1710        const char *p;
1711
1712        f = fopen(git_path_head_file(), "r");
1713        if (!f && errno == ENOENT) {
1714                /*
1715                 * There is no multiple-cherry-pick in progress.
1716                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1717                 * a single-cherry-pick in progress, abort that.
1718                 */
1719                return rollback_single_pick();
1720        }
1721        if (!f)
1722                return error_errno(_("cannot open '%s'"), git_path_head_file());
1723        if (strbuf_getline_lf(&buf, f)) {
1724                error(_("cannot read '%s': %s"), git_path_head_file(),
1725                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1726                fclose(f);
1727                goto fail;
1728        }
1729        fclose(f);
1730        if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
1731                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1732                        git_path_head_file());
1733                goto fail;
1734        }
1735        if (is_null_oid(&oid)) {
1736                error(_("cannot abort from a branch yet to be born"));
1737                goto fail;
1738        }
1739
1740        if (!rollback_is_safe()) {
1741                /* Do not error, just do not rollback */
1742                warning(_("You seem to have moved HEAD. "
1743                          "Not rewinding, check your HEAD!"));
1744        } else
1745        if (reset_for_rollback(&oid))
1746                goto fail;
1747        strbuf_release(&buf);
1748        return sequencer_remove_state(opts);
1749fail:
1750        strbuf_release(&buf);
1751        return -1;
1752}
1753
1754static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1755{
1756        static struct lock_file todo_lock;
1757        const char *todo_path = get_todo_path(opts);
1758        int next = todo_list->current, offset, fd;
1759
1760        /*
1761         * rebase -i writes "git-rebase-todo" without the currently executing
1762         * command, appending it to "done" instead.
1763         */
1764        if (is_rebase_i(opts))
1765                next++;
1766
1767        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1768        if (fd < 0)
1769                return error_errno(_("could not lock '%s'"), todo_path);
1770        offset = next < todo_list->nr ?
1771                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1772        if (write_in_full(fd, todo_list->buf.buf + offset,
1773                        todo_list->buf.len - offset) < 0)
1774                return error_errno(_("could not write to '%s'"), todo_path);
1775        if (commit_lock_file(&todo_lock) < 0)
1776                return error(_("failed to finalize '%s'."), todo_path);
1777
1778        if (is_rebase_i(opts)) {
1779                const char *done_path = rebase_path_done();
1780                int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1781                int prev_offset = !next ? 0 :
1782                        todo_list->items[next - 1].offset_in_buf;
1783
1784                if (fd >= 0 && offset > prev_offset &&
1785                    write_in_full(fd, todo_list->buf.buf + prev_offset,
1786                                  offset - prev_offset) < 0) {
1787                        close(fd);
1788                        return error_errno(_("could not write to '%s'"),
1789                                           done_path);
1790                }
1791                if (fd >= 0)
1792                        close(fd);
1793        }
1794        return 0;
1795}
1796
1797static int save_opts(struct replay_opts *opts)
1798{
1799        const char *opts_file = git_path_opts_file();
1800        int res = 0;
1801
1802        if (opts->no_commit)
1803                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1804        if (opts->edit)
1805                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1806        if (opts->signoff)
1807                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1808        if (opts->record_origin)
1809                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1810        if (opts->allow_ff)
1811                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1812        if (opts->mainline) {
1813                struct strbuf buf = STRBUF_INIT;
1814                strbuf_addf(&buf, "%d", opts->mainline);
1815                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1816                strbuf_release(&buf);
1817        }
1818        if (opts->strategy)
1819                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1820        if (opts->gpg_sign)
1821                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1822        if (opts->xopts) {
1823                int i;
1824                for (i = 0; i < opts->xopts_nr; i++)
1825                        res |= git_config_set_multivar_in_file_gently(opts_file,
1826                                                        "options.strategy-option",
1827                                                        opts->xopts[i], "^$", 0);
1828        }
1829        if (opts->allow_rerere_auto)
1830                res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
1831                                                     opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
1832                                                     "true" : "false");
1833        return res;
1834}
1835
1836static int make_patch(struct commit *commit, struct replay_opts *opts)
1837{
1838        struct strbuf buf = STRBUF_INIT;
1839        struct rev_info log_tree_opt;
1840        const char *subject, *p;
1841        int res = 0;
1842
1843        p = short_commit_name(commit);
1844        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1845                return -1;
1846
1847        strbuf_addf(&buf, "%s/patch", get_dir(opts));
1848        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1849        init_revisions(&log_tree_opt, NULL);
1850        log_tree_opt.abbrev = 0;
1851        log_tree_opt.diff = 1;
1852        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1853        log_tree_opt.disable_stdin = 1;
1854        log_tree_opt.no_commit_id = 1;
1855        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1856        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1857        if (!log_tree_opt.diffopt.file)
1858                res |= error_errno(_("could not open '%s'"), buf.buf);
1859        else {
1860                res |= log_tree_commit(&log_tree_opt, commit);
1861                fclose(log_tree_opt.diffopt.file);
1862        }
1863        strbuf_reset(&buf);
1864
1865        strbuf_addf(&buf, "%s/message", get_dir(opts));
1866        if (!file_exists(buf.buf)) {
1867                const char *commit_buffer = get_commit_buffer(commit, NULL);
1868                find_commit_subject(commit_buffer, &subject);
1869                res |= write_message(subject, strlen(subject), buf.buf, 1);
1870                unuse_commit_buffer(commit, commit_buffer);
1871        }
1872        strbuf_release(&buf);
1873
1874        return res;
1875}
1876
1877static int intend_to_amend(void)
1878{
1879        struct object_id head;
1880        char *p;
1881
1882        if (get_oid("HEAD", &head))
1883                return error(_("cannot read HEAD"));
1884
1885        p = oid_to_hex(&head);
1886        return write_message(p, strlen(p), rebase_path_amend(), 1);
1887}
1888
1889static int error_with_patch(struct commit *commit,
1890        const char *subject, int subject_len,
1891        struct replay_opts *opts, int exit_code, int to_amend)
1892{
1893        if (make_patch(commit, opts))
1894                return -1;
1895
1896        if (to_amend) {
1897                if (intend_to_amend())
1898                        return -1;
1899
1900                fprintf(stderr, "You can amend the commit now, with\n"
1901                        "\n"
1902                        "  git commit --amend %s\n"
1903                        "\n"
1904                        "Once you are satisfied with your changes, run\n"
1905                        "\n"
1906                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
1907        } else if (exit_code)
1908                fprintf(stderr, "Could not apply %s... %.*s\n",
1909                        short_commit_name(commit), subject_len, subject);
1910
1911        return exit_code;
1912}
1913
1914static int error_failed_squash(struct commit *commit,
1915        struct replay_opts *opts, int subject_len, const char *subject)
1916{
1917        if (rename(rebase_path_squash_msg(), rebase_path_message()))
1918                return error(_("could not rename '%s' to '%s'"),
1919                        rebase_path_squash_msg(), rebase_path_message());
1920        unlink(rebase_path_fixup_msg());
1921        unlink(git_path_merge_msg());
1922        if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
1923                return error(_("could not copy '%s' to '%s'"),
1924                             rebase_path_message(), git_path_merge_msg());
1925        return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1926}
1927
1928static int do_exec(const char *command_line)
1929{
1930        struct argv_array child_env = ARGV_ARRAY_INIT;
1931        const char *child_argv[] = { NULL, NULL };
1932        int dirty, status;
1933
1934        fprintf(stderr, "Executing: %s\n", command_line);
1935        child_argv[0] = command_line;
1936        argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
1937        status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
1938                                          child_env.argv);
1939
1940        /* force re-reading of the cache */
1941        if (discard_cache() < 0 || read_cache() < 0)
1942                return error(_("could not read index"));
1943
1944        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1945
1946        if (status) {
1947                warning(_("execution failed: %s\n%s"
1948                          "You can fix the problem, and then run\n"
1949                          "\n"
1950                          "  git rebase --continue\n"
1951                          "\n"),
1952                        command_line,
1953                        dirty ? N_("and made changes to the index and/or the "
1954                                "working tree\n") : "");
1955                if (status == 127)
1956                        /* command not found */
1957                        status = 1;
1958        } else if (dirty) {
1959                warning(_("execution succeeded: %s\nbut "
1960                          "left changes to the index and/or the working tree\n"
1961                          "Commit or stash your changes, and then run\n"
1962                          "\n"
1963                          "  git rebase --continue\n"
1964                          "\n"), command_line);
1965                status = 1;
1966        }
1967
1968        argv_array_clear(&child_env);
1969
1970        return status;
1971}
1972
1973static int safe_append(const char *filename, const char *fmt, ...)
1974{
1975        va_list ap;
1976        struct lock_file lock = LOCK_INIT;
1977        int fd = hold_lock_file_for_update(&lock, filename,
1978                                           LOCK_REPORT_ON_ERROR);
1979        struct strbuf buf = STRBUF_INIT;
1980
1981        if (fd < 0)
1982                return -1;
1983
1984        if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT)
1985                return error_errno(_("could not read '%s'"), filename);
1986        strbuf_complete(&buf, '\n');
1987        va_start(ap, fmt);
1988        strbuf_vaddf(&buf, fmt, ap);
1989        va_end(ap);
1990
1991        if (write_in_full(fd, buf.buf, buf.len) < 0) {
1992                error_errno(_("could not write to '%s'"), filename);
1993                strbuf_release(&buf);
1994                rollback_lock_file(&lock);
1995                return -1;
1996        }
1997        if (commit_lock_file(&lock) < 0) {
1998                strbuf_release(&buf);
1999                rollback_lock_file(&lock);
2000                return error(_("failed to finalize '%s'"), filename);
2001        }
2002
2003        strbuf_release(&buf);
2004        return 0;
2005}
2006
2007static int do_label(const char *name, int len)
2008{
2009        struct ref_store *refs = get_main_ref_store();
2010        struct ref_transaction *transaction;
2011        struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2012        struct strbuf msg = STRBUF_INIT;
2013        int ret = 0;
2014        struct object_id head_oid;
2015
2016        if (len == 1 && *name == '#')
2017                return error("Illegal label name: '%.*s'", len, name);
2018
2019        strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2020        strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2021
2022        transaction = ref_store_transaction_begin(refs, &err);
2023        if (!transaction) {
2024                error("%s", err.buf);
2025                ret = -1;
2026        } else if (get_oid("HEAD", &head_oid)) {
2027                error(_("could not read HEAD"));
2028                ret = -1;
2029        } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2030                                          NULL, 0, msg.buf, &err) < 0 ||
2031                   ref_transaction_commit(transaction, &err)) {
2032                error("%s", err.buf);
2033                ret = -1;
2034        }
2035        ref_transaction_free(transaction);
2036        strbuf_release(&err);
2037        strbuf_release(&msg);
2038
2039        if (!ret)
2040                ret = safe_append(rebase_path_refs_to_delete(),
2041                                  "%s\n", ref_name.buf);
2042        strbuf_release(&ref_name);
2043
2044        return ret;
2045}
2046
2047static int do_reset(const char *name, int len, struct replay_opts *opts)
2048{
2049        struct strbuf ref_name = STRBUF_INIT;
2050        struct object_id oid;
2051        struct lock_file lock = LOCK_INIT;
2052        struct tree_desc desc;
2053        struct tree *tree;
2054        struct unpack_trees_options unpack_tree_opts;
2055        int ret = 0, i;
2056
2057        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2058                return -1;
2059
2060        /* Determine the length of the label */
2061        for (i = 0; i < len; i++)
2062                if (isspace(name[i]))
2063                        len = i;
2064
2065        strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2066        if (get_oid(ref_name.buf, &oid) &&
2067            get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2068                error(_("could not read '%s'"), ref_name.buf);
2069                rollback_lock_file(&lock);
2070                strbuf_release(&ref_name);
2071                return -1;
2072        }
2073
2074        memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2075        unpack_tree_opts.head_idx = 1;
2076        unpack_tree_opts.src_index = &the_index;
2077        unpack_tree_opts.dst_index = &the_index;
2078        unpack_tree_opts.fn = oneway_merge;
2079        unpack_tree_opts.merge = 1;
2080        unpack_tree_opts.update = 1;
2081        unpack_tree_opts.reset = 1;
2082
2083        if (read_cache_unmerged()) {
2084                rollback_lock_file(&lock);
2085                strbuf_release(&ref_name);
2086                return error_resolve_conflict(_(action_name(opts)));
2087        }
2088
2089        if (!fill_tree_descriptor(&desc, &oid)) {
2090                error(_("failed to find tree of %s"), oid_to_hex(&oid));
2091                rollback_lock_file(&lock);
2092                free((void *)desc.buffer);
2093                strbuf_release(&ref_name);
2094                return -1;
2095        }
2096
2097        if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2098                rollback_lock_file(&lock);
2099                free((void *)desc.buffer);
2100                strbuf_release(&ref_name);
2101                return -1;
2102        }
2103
2104        tree = parse_tree_indirect(&oid);
2105        prime_cache_tree(&the_index, tree);
2106
2107        if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2108                ret = error(_("could not write index"));
2109        free((void *)desc.buffer);
2110
2111        if (!ret) {
2112                struct strbuf msg = STRBUF_INIT;
2113
2114                strbuf_addf(&msg, "(rebase -i) reset '%.*s'", len, name);
2115                ret = update_ref(msg.buf, "HEAD", &oid, NULL, 0,
2116                                 UPDATE_REFS_MSG_ON_ERR);
2117                strbuf_release(&msg);
2118        }
2119
2120        strbuf_release(&ref_name);
2121        return ret;
2122}
2123
2124static int do_merge(struct commit *commit, const char *arg, int arg_len,
2125                    int run_commit_flags, struct replay_opts *opts)
2126{
2127        int merge_arg_len;
2128        struct strbuf ref_name = STRBUF_INIT;
2129        struct commit *head_commit, *merge_commit, *i;
2130        struct commit_list *common, *j, *reversed = NULL;
2131        struct merge_options o;
2132        int can_fast_forward, ret;
2133        static struct lock_file lock;
2134
2135        for (merge_arg_len = 0; merge_arg_len < arg_len; merge_arg_len++)
2136                if (isspace(arg[merge_arg_len]))
2137                        break;
2138
2139        if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2140                return -1;
2141
2142        head_commit = lookup_commit_reference_by_name("HEAD");
2143        if (!head_commit) {
2144                rollback_lock_file(&lock);
2145                return error(_("cannot merge without a current revision"));
2146        }
2147
2148        if (commit) {
2149                const char *message = get_commit_buffer(commit, NULL);
2150                const char *body;
2151                int len;
2152
2153                if (!message) {
2154                        rollback_lock_file(&lock);
2155                        return error(_("could not get commit message of '%s'"),
2156                                     oid_to_hex(&commit->object.oid));
2157                }
2158                write_author_script(message);
2159                find_commit_subject(message, &body);
2160                len = strlen(body);
2161                if (write_message(body, len, git_path_merge_msg(), 0) < 0) {
2162                        error_errno(_("could not write '%s'"),
2163                                    git_path_merge_msg());
2164                        unuse_commit_buffer(commit, message);
2165                        rollback_lock_file(&lock);
2166                        return -1;
2167                }
2168                unuse_commit_buffer(commit, message);
2169        } else {
2170                const char *p = arg + merge_arg_len;
2171                struct strbuf buf = STRBUF_INIT;
2172                int len;
2173
2174                strbuf_addf(&buf, "author %s", git_author_info(0));
2175                write_author_script(buf.buf);
2176                strbuf_reset(&buf);
2177
2178                p += strspn(p, " \t");
2179                if (*p == '#' && isspace(p[1]))
2180                        p += 1 + strspn(p + 1, " \t");
2181                if (*p)
2182                        len = strlen(p);
2183                else {
2184                        strbuf_addf(&buf, "Merge branch '%.*s'",
2185                                    merge_arg_len, arg);
2186                        p = buf.buf;
2187                        len = buf.len;
2188                }
2189
2190                if (write_message(p, len, git_path_merge_msg(), 0) < 0) {
2191                        error_errno(_("could not write '%s'"),
2192                                    git_path_merge_msg());
2193                        strbuf_release(&buf);
2194                        rollback_lock_file(&lock);
2195                        return -1;
2196                }
2197                strbuf_release(&buf);
2198        }
2199
2200        /*
2201         * If HEAD is not identical to the parent of the original merge commit,
2202         * we cannot fast-forward.
2203         */
2204        can_fast_forward = opts->allow_ff && commit && commit->parents &&
2205                !oidcmp(&commit->parents->item->object.oid,
2206                        &head_commit->object.oid);
2207
2208        strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
2209        merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2210        if (!merge_commit) {
2211                /* fall back to non-rewritten ref or commit */
2212                strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
2213                merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2214        }
2215        if (!merge_commit) {
2216                error(_("could not resolve '%s'"), ref_name.buf);
2217                strbuf_release(&ref_name);
2218                rollback_lock_file(&lock);
2219                return -1;
2220        }
2221
2222        if (can_fast_forward && commit->parents->next &&
2223            !commit->parents->next->next &&
2224            !oidcmp(&commit->parents->next->item->object.oid,
2225                    &merge_commit->object.oid)) {
2226                strbuf_release(&ref_name);
2227                rollback_lock_file(&lock);
2228                return fast_forward_to(&commit->object.oid,
2229                                       &head_commit->object.oid, 0, opts);
2230        }
2231
2232        write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
2233                      git_path_merge_head(), 0);
2234        write_message("no-ff", 5, git_path_merge_mode(), 0);
2235
2236        common = get_merge_bases(head_commit, merge_commit);
2237        for (j = common; j; j = j->next)
2238                commit_list_insert(j->item, &reversed);
2239        free_commit_list(common);
2240
2241        read_cache();
2242        init_merge_options(&o);
2243        o.branch1 = "HEAD";
2244        o.branch2 = ref_name.buf;
2245        o.buffer_output = 2;
2246
2247        ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2248        if (ret <= 0)
2249                fputs(o.obuf.buf, stdout);
2250        strbuf_release(&o.obuf);
2251        if (ret < 0) {
2252                strbuf_release(&ref_name);
2253                rollback_lock_file(&lock);
2254                return error(_("conflicts while merging '%.*s'"),
2255                             merge_arg_len, arg);
2256        }
2257
2258        if (active_cache_changed &&
2259            write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2260                strbuf_release(&ref_name);
2261                return error(_("merge: Unable to write new index file"));
2262        }
2263        rollback_lock_file(&lock);
2264
2265        ret = run_git_commit(git_path_merge_msg(), opts, run_commit_flags);
2266        strbuf_release(&ref_name);
2267
2268        return ret;
2269}
2270
2271static int is_final_fixup(struct todo_list *todo_list)
2272{
2273        int i = todo_list->current;
2274
2275        if (!is_fixup(todo_list->items[i].command))
2276                return 0;
2277
2278        while (++i < todo_list->nr)
2279                if (is_fixup(todo_list->items[i].command))
2280                        return 0;
2281                else if (!is_noop(todo_list->items[i].command))
2282                        break;
2283        return 1;
2284}
2285
2286static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2287{
2288        int i;
2289
2290        for (i = todo_list->current + offset; i < todo_list->nr; i++)
2291                if (!is_noop(todo_list->items[i].command))
2292                        return todo_list->items[i].command;
2293
2294        return -1;
2295}
2296
2297static int apply_autostash(struct replay_opts *opts)
2298{
2299        struct strbuf stash_sha1 = STRBUF_INIT;
2300        struct child_process child = CHILD_PROCESS_INIT;
2301        int ret = 0;
2302
2303        if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2304                strbuf_release(&stash_sha1);
2305                return 0;
2306        }
2307        strbuf_trim(&stash_sha1);
2308
2309        child.git_cmd = 1;
2310        child.no_stdout = 1;
2311        child.no_stderr = 1;
2312        argv_array_push(&child.args, "stash");
2313        argv_array_push(&child.args, "apply");
2314        argv_array_push(&child.args, stash_sha1.buf);
2315        if (!run_command(&child))
2316                fprintf(stderr, _("Applied autostash.\n"));
2317        else {
2318                struct child_process store = CHILD_PROCESS_INIT;
2319
2320                store.git_cmd = 1;
2321                argv_array_push(&store.args, "stash");
2322                argv_array_push(&store.args, "store");
2323                argv_array_push(&store.args, "-m");
2324                argv_array_push(&store.args, "autostash");
2325                argv_array_push(&store.args, "-q");
2326                argv_array_push(&store.args, stash_sha1.buf);
2327                if (run_command(&store))
2328                        ret = error(_("cannot store %s"), stash_sha1.buf);
2329                else
2330                        fprintf(stderr,
2331                                _("Applying autostash resulted in conflicts.\n"
2332                                  "Your changes are safe in the stash.\n"
2333                                  "You can run \"git stash pop\" or"
2334                                  " \"git stash drop\" at any time.\n"));
2335        }
2336
2337        strbuf_release(&stash_sha1);
2338        return ret;
2339}
2340
2341static const char *reflog_message(struct replay_opts *opts,
2342        const char *sub_action, const char *fmt, ...)
2343{
2344        va_list ap;
2345        static struct strbuf buf = STRBUF_INIT;
2346
2347        va_start(ap, fmt);
2348        strbuf_reset(&buf);
2349        strbuf_addstr(&buf, action_name(opts));
2350        if (sub_action)
2351                strbuf_addf(&buf, " (%s)", sub_action);
2352        if (fmt) {
2353                strbuf_addstr(&buf, ": ");
2354                strbuf_vaddf(&buf, fmt, ap);
2355        }
2356        va_end(ap);
2357
2358        return buf.buf;
2359}
2360
2361static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2362{
2363        int res = 0;
2364
2365        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2366        if (opts->allow_ff)
2367                assert(!(opts->signoff || opts->no_commit ||
2368                                opts->record_origin || opts->edit));
2369        if (read_and_refresh_cache(opts))
2370                return -1;
2371
2372        while (todo_list->current < todo_list->nr) {
2373                struct todo_item *item = todo_list->items + todo_list->current;
2374                if (save_todo(todo_list, opts))
2375                        return -1;
2376                if (is_rebase_i(opts)) {
2377                        if (item->command != TODO_COMMENT) {
2378                                FILE *f = fopen(rebase_path_msgnum(), "w");
2379
2380                                todo_list->done_nr++;
2381
2382                                if (f) {
2383                                        fprintf(f, "%d\n", todo_list->done_nr);
2384                                        fclose(f);
2385                                }
2386                                fprintf(stderr, "Rebasing (%d/%d)%s",
2387                                        todo_list->done_nr,
2388                                        todo_list->total_nr,
2389                                        opts->verbose ? "\n" : "\r");
2390                        }
2391                        unlink(rebase_path_message());
2392                        unlink(rebase_path_author_script());
2393                        unlink(rebase_path_stopped_sha());
2394                        unlink(rebase_path_amend());
2395                }
2396                if (item->command <= TODO_SQUASH) {
2397                        if (is_rebase_i(opts))
2398                                setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2399                                        command_to_string(item->command), NULL),
2400                                        1);
2401                        res = do_pick_commit(item->command, item->commit,
2402                                        opts, is_final_fixup(todo_list));
2403                        if (is_rebase_i(opts) && res < 0) {
2404                                /* Reschedule */
2405                                todo_list->current--;
2406                                if (save_todo(todo_list, opts))
2407                                        return -1;
2408                        }
2409                        if (item->command == TODO_EDIT) {
2410                                struct commit *commit = item->commit;
2411                                if (!res)
2412                                        fprintf(stderr,
2413                                                _("Stopped at %s...  %.*s\n"),
2414                                                short_commit_name(commit),
2415                                                item->arg_len, item->arg);
2416                                return error_with_patch(commit,
2417                                        item->arg, item->arg_len, opts, res,
2418                                        !res);
2419                        }
2420                        if (is_rebase_i(opts) && !res)
2421                                record_in_rewritten(&item->commit->object.oid,
2422                                        peek_command(todo_list, 1));
2423                        if (res && is_fixup(item->command)) {
2424                                if (res == 1)
2425                                        intend_to_amend();
2426                                return error_failed_squash(item->commit, opts,
2427                                        item->arg_len, item->arg);
2428                        } else if (res && is_rebase_i(opts))
2429                                return res | error_with_patch(item->commit,
2430                                        item->arg, item->arg_len, opts, res,
2431                                        item->command == TODO_REWORD);
2432                } else if (item->command == TODO_EXEC) {
2433                        char *end_of_arg = (char *)(item->arg + item->arg_len);
2434                        int saved = *end_of_arg;
2435                        struct stat st;
2436
2437                        *end_of_arg = '\0';
2438                        res = do_exec(item->arg);
2439                        *end_of_arg = saved;
2440
2441                        /* Reread the todo file if it has changed. */
2442                        if (res)
2443                                ; /* fall through */
2444                        else if (stat(get_todo_path(opts), &st))
2445                                res = error_errno(_("could not stat '%s'"),
2446                                                  get_todo_path(opts));
2447                        else if (match_stat_data(&todo_list->stat, &st)) {
2448                                todo_list_release(todo_list);
2449                                if (read_populate_todo(todo_list, opts))
2450                                        res = -1; /* message was printed */
2451                                /* `current` will be incremented below */
2452                                todo_list->current = -1;
2453                        }
2454                } else if (item->command == TODO_LABEL)
2455                        res = do_label(item->arg, item->arg_len);
2456                else if (item->command == TODO_RESET)
2457                        res = do_reset(item->arg, item->arg_len, opts);
2458                else if (item->command == TODO_MERGE ||
2459                         item->command == TODO_MERGE_AND_EDIT)
2460                        res = do_merge(item->commit, item->arg, item->arg_len,
2461                                       item->command == TODO_MERGE_AND_EDIT ?
2462                                       EDIT_MSG | VERIFY_MSG : 0, opts);
2463                else if (!is_noop(item->command))
2464                        return error(_("unknown command %d"), item->command);
2465
2466                todo_list->current++;
2467                if (res)
2468                        return res;
2469        }
2470
2471        if (is_rebase_i(opts)) {
2472                struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2473                struct stat st;
2474
2475                /* Stopped in the middle, as planned? */
2476                if (todo_list->current < todo_list->nr)
2477                        return 0;
2478
2479                if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2480                                starts_with(head_ref.buf, "refs/")) {
2481                        const char *msg;
2482                        struct object_id head, orig;
2483                        int res;
2484
2485                        if (get_oid("HEAD", &head)) {
2486                                res = error(_("cannot read HEAD"));
2487cleanup_head_ref:
2488                                strbuf_release(&head_ref);
2489                                strbuf_release(&buf);
2490                                return res;
2491                        }
2492                        if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2493                                        get_oid_hex(buf.buf, &orig)) {
2494                                res = error(_("could not read orig-head"));
2495                                goto cleanup_head_ref;
2496                        }
2497                        strbuf_reset(&buf);
2498                        if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2499                                res = error(_("could not read 'onto'"));
2500                                goto cleanup_head_ref;
2501                        }
2502                        msg = reflog_message(opts, "finish", "%s onto %s",
2503                                head_ref.buf, buf.buf);
2504                        if (update_ref(msg, head_ref.buf, &head, &orig,
2505                                       REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2506                                res = error(_("could not update %s"),
2507                                        head_ref.buf);
2508                                goto cleanup_head_ref;
2509                        }
2510                        msg = reflog_message(opts, "finish", "returning to %s",
2511                                head_ref.buf);
2512                        if (create_symref("HEAD", head_ref.buf, msg)) {
2513                                res = error(_("could not update HEAD to %s"),
2514                                        head_ref.buf);
2515                                goto cleanup_head_ref;
2516                        }
2517                        strbuf_reset(&buf);
2518                }
2519
2520                if (opts->verbose) {
2521                        struct rev_info log_tree_opt;
2522                        struct object_id orig, head;
2523
2524                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2525                        init_revisions(&log_tree_opt, NULL);
2526                        log_tree_opt.diff = 1;
2527                        log_tree_opt.diffopt.output_format =
2528                                DIFF_FORMAT_DIFFSTAT;
2529                        log_tree_opt.disable_stdin = 1;
2530
2531                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2532                            !get_oid(buf.buf, &orig) &&
2533                            !get_oid("HEAD", &head)) {
2534                                diff_tree_oid(&orig, &head, "",
2535                                              &log_tree_opt.diffopt);
2536                                log_tree_diff_flush(&log_tree_opt);
2537                        }
2538                }
2539                flush_rewritten_pending();
2540                if (!stat(rebase_path_rewritten_list(), &st) &&
2541                                st.st_size > 0) {
2542                        struct child_process child = CHILD_PROCESS_INIT;
2543                        const char *post_rewrite_hook =
2544                                find_hook("post-rewrite");
2545
2546                        child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2547                        child.git_cmd = 1;
2548                        argv_array_push(&child.args, "notes");
2549                        argv_array_push(&child.args, "copy");
2550                        argv_array_push(&child.args, "--for-rewrite=rebase");
2551                        /* we don't care if this copying failed */
2552                        run_command(&child);
2553
2554                        if (post_rewrite_hook) {
2555                                struct child_process hook = CHILD_PROCESS_INIT;
2556
2557                                hook.in = open(rebase_path_rewritten_list(),
2558                                        O_RDONLY);
2559                                hook.stdout_to_stderr = 1;
2560                                argv_array_push(&hook.args, post_rewrite_hook);
2561                                argv_array_push(&hook.args, "rebase");
2562                                /* we don't care if this hook failed */
2563                                run_command(&hook);
2564                        }
2565                }
2566                apply_autostash(opts);
2567
2568                fprintf(stderr, "Successfully rebased and updated %s.\n",
2569                        head_ref.buf);
2570
2571                strbuf_release(&buf);
2572                strbuf_release(&head_ref);
2573        }
2574
2575        /*
2576         * Sequence of picks finished successfully; cleanup by
2577         * removing the .git/sequencer directory
2578         */
2579        return sequencer_remove_state(opts);
2580}
2581
2582static int continue_single_pick(void)
2583{
2584        const char *argv[] = { "commit", NULL };
2585
2586        if (!file_exists(git_path_cherry_pick_head()) &&
2587            !file_exists(git_path_revert_head()))
2588                return error(_("no cherry-pick or revert in progress"));
2589        return run_command_v_opt(argv, RUN_GIT_CMD);
2590}
2591
2592static int commit_staged_changes(struct replay_opts *opts)
2593{
2594        unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2595
2596        if (has_unstaged_changes(1))
2597                return error(_("cannot rebase: You have unstaged changes."));
2598        if (!has_uncommitted_changes(0)) {
2599                const char *cherry_pick_head = git_path_cherry_pick_head();
2600
2601                if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2602                        return error(_("could not remove CHERRY_PICK_HEAD"));
2603                return 0;
2604        }
2605
2606        if (file_exists(rebase_path_amend())) {
2607                struct strbuf rev = STRBUF_INIT;
2608                struct object_id head, to_amend;
2609
2610                if (get_oid("HEAD", &head))
2611                        return error(_("cannot amend non-existing commit"));
2612                if (!read_oneliner(&rev, rebase_path_amend(), 0))
2613                        return error(_("invalid file: '%s'"), rebase_path_amend());
2614                if (get_oid_hex(rev.buf, &to_amend))
2615                        return error(_("invalid contents: '%s'"),
2616                                rebase_path_amend());
2617                if (oidcmp(&head, &to_amend))
2618                        return error(_("\nYou have uncommitted changes in your "
2619                                       "working tree. Please, commit them\n"
2620                                       "first and then run 'git rebase "
2621                                       "--continue' again."));
2622
2623                strbuf_release(&rev);
2624                flags |= AMEND_MSG;
2625        }
2626
2627        if (run_git_commit(rebase_path_message(), opts, flags))
2628                return error(_("could not commit staged changes."));
2629        unlink(rebase_path_amend());
2630        return 0;
2631}
2632
2633int sequencer_continue(struct replay_opts *opts)
2634{
2635        struct todo_list todo_list = TODO_LIST_INIT;
2636        int res;
2637
2638        if (read_and_refresh_cache(opts))
2639                return -1;
2640
2641        if (is_rebase_i(opts)) {
2642                if (commit_staged_changes(opts))
2643                        return -1;
2644        } else if (!file_exists(get_todo_path(opts)))
2645                return continue_single_pick();
2646        if (read_populate_opts(opts))
2647                return -1;
2648        if ((res = read_populate_todo(&todo_list, opts)))
2649                goto release_todo_list;
2650
2651        if (!is_rebase_i(opts)) {
2652                /* Verify that the conflict has been resolved */
2653                if (file_exists(git_path_cherry_pick_head()) ||
2654                    file_exists(git_path_revert_head())) {
2655                        res = continue_single_pick();
2656                        if (res)
2657                                goto release_todo_list;
2658                }
2659                if (index_differs_from("HEAD", NULL, 0)) {
2660                        res = error_dirty_index(opts);
2661                        goto release_todo_list;
2662                }
2663                todo_list.current++;
2664        } else if (file_exists(rebase_path_stopped_sha())) {
2665                struct strbuf buf = STRBUF_INIT;
2666                struct object_id oid;
2667
2668                if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2669                    !get_oid_committish(buf.buf, &oid))
2670                        record_in_rewritten(&oid, peek_command(&todo_list, 0));
2671                strbuf_release(&buf);
2672        }
2673
2674        res = pick_commits(&todo_list, opts);
2675release_todo_list:
2676        todo_list_release(&todo_list);
2677        return res;
2678}
2679
2680static int single_pick(struct commit *cmit, struct replay_opts *opts)
2681{
2682        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2683        return do_pick_commit(opts->action == REPLAY_PICK ?
2684                TODO_PICK : TODO_REVERT, cmit, opts, 0);
2685}
2686
2687int sequencer_pick_revisions(struct replay_opts *opts)
2688{
2689        struct todo_list todo_list = TODO_LIST_INIT;
2690        struct object_id oid;
2691        int i, res;
2692
2693        assert(opts->revs);
2694        if (read_and_refresh_cache(opts))
2695                return -1;
2696
2697        for (i = 0; i < opts->revs->pending.nr; i++) {
2698                struct object_id oid;
2699                const char *name = opts->revs->pending.objects[i].name;
2700
2701                /* This happens when using --stdin. */
2702                if (!strlen(name))
2703                        continue;
2704
2705                if (!get_oid(name, &oid)) {
2706                        if (!lookup_commit_reference_gently(&oid, 1)) {
2707                                enum object_type type = sha1_object_info(oid.hash, NULL);
2708                                return error(_("%s: can't cherry-pick a %s"),
2709                                        name, typename(type));
2710                        }
2711                } else
2712                        return error(_("%s: bad revision"), name);
2713        }
2714
2715        /*
2716         * If we were called as "git cherry-pick <commit>", just
2717         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2718         * REVERT_HEAD, and don't touch the sequencer state.
2719         * This means it is possible to cherry-pick in the middle
2720         * of a cherry-pick sequence.
2721         */
2722        if (opts->revs->cmdline.nr == 1 &&
2723            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2724            opts->revs->no_walk &&
2725            !opts->revs->cmdline.rev->flags) {
2726                struct commit *cmit;
2727                if (prepare_revision_walk(opts->revs))
2728                        return error(_("revision walk setup failed"));
2729                cmit = get_revision(opts->revs);
2730                if (!cmit || get_revision(opts->revs))
2731                        return error("BUG: expected exactly one commit from walk");
2732                return single_pick(cmit, opts);
2733        }
2734
2735        /*
2736         * Start a new cherry-pick/ revert sequence; but
2737         * first, make sure that an existing one isn't in
2738         * progress
2739         */
2740
2741        if (walk_revs_populate_todo(&todo_list, opts) ||
2742                        create_seq_dir() < 0)
2743                return -1;
2744        if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2745                return error(_("can't revert as initial commit"));
2746        if (save_head(oid_to_hex(&oid)))
2747                return -1;
2748        if (save_opts(opts))
2749                return -1;
2750        update_abort_safety_file();
2751        res = pick_commits(&todo_list, opts);
2752        todo_list_release(&todo_list);
2753        return res;
2754}
2755
2756void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2757{
2758        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2759        struct strbuf sob = STRBUF_INIT;
2760        int has_footer;
2761
2762        strbuf_addstr(&sob, sign_off_header);
2763        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2764                                getenv("GIT_COMMITTER_EMAIL")));
2765        strbuf_addch(&sob, '\n');
2766
2767        if (!ignore_footer)
2768                strbuf_complete_line(msgbuf);
2769
2770        /*
2771         * If the whole message buffer is equal to the sob, pretend that we
2772         * found a conforming footer with a matching sob
2773         */
2774        if (msgbuf->len - ignore_footer == sob.len &&
2775            !strncmp(msgbuf->buf, sob.buf, sob.len))
2776                has_footer = 3;
2777        else
2778                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2779
2780        if (!has_footer) {
2781                const char *append_newlines = NULL;
2782                size_t len = msgbuf->len - ignore_footer;
2783
2784                if (!len) {
2785                        /*
2786                         * The buffer is completely empty.  Leave foom for
2787                         * the title and body to be filled in by the user.
2788                         */
2789                        append_newlines = "\n\n";
2790                } else if (len == 1) {
2791                        /*
2792                         * Buffer contains a single newline.  Add another
2793                         * so that we leave room for the title and body.
2794                         */
2795                        append_newlines = "\n";
2796                } else if (msgbuf->buf[len - 2] != '\n') {
2797                        /*
2798                         * Buffer ends with a single newline.  Add another
2799                         * so that there is an empty line between the message
2800                         * body and the sob.
2801                         */
2802                        append_newlines = "\n";
2803                } /* else, the buffer already ends with two newlines. */
2804
2805                if (append_newlines)
2806                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2807                                append_newlines, strlen(append_newlines));
2808        }
2809
2810        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2811                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2812                                sob.buf, sob.len);
2813
2814        strbuf_release(&sob);
2815}
2816
2817int sequencer_make_script(FILE *out, int argc, const char **argv,
2818                          unsigned flags)
2819{
2820        char *format = NULL;
2821        struct pretty_print_context pp = {0};
2822        struct strbuf buf = STRBUF_INIT;
2823        struct rev_info revs;
2824        struct commit *commit;
2825        int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
2826        const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
2827
2828        init_revisions(&revs, NULL);
2829        revs.verbose_header = 1;
2830        revs.max_parents = 1;
2831        revs.cherry_pick = 1;
2832        revs.limited = 1;
2833        revs.reverse = 1;
2834        revs.right_only = 1;
2835        revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2836        revs.topo_order = 1;
2837
2838        revs.pretty_given = 1;
2839        git_config_get_string("rebase.instructionFormat", &format);
2840        if (!format || !*format) {
2841                free(format);
2842                format = xstrdup("%s");
2843        }
2844        get_commit_format(format, &revs);
2845        free(format);
2846        pp.fmt = revs.commit_format;
2847        pp.output_encoding = get_log_output_encoding();
2848
2849        if (setup_revisions(argc, argv, &revs, NULL) > 1)
2850                return error(_("make_script: unhandled options"));
2851
2852        if (prepare_revision_walk(&revs) < 0)
2853                return error(_("make_script: error preparing revisions"));
2854
2855        while ((commit = get_revision(&revs))) {
2856                strbuf_reset(&buf);
2857                if (!keep_empty && is_original_commit_empty(commit))
2858                        strbuf_addf(&buf, "%c ", comment_line_char);
2859                strbuf_addf(&buf, "%s %s ", insn,
2860                            oid_to_hex(&commit->object.oid));
2861                pretty_print_commit(&pp, commit, &buf);
2862                strbuf_addch(&buf, '\n');
2863                fputs(buf.buf, out);
2864        }
2865        strbuf_release(&buf);
2866        return 0;
2867}
2868
2869/*
2870 * Add commands after pick and (series of) squash/fixup commands
2871 * in the todo list.
2872 */
2873int sequencer_add_exec_commands(const char *commands)
2874{
2875        const char *todo_file = rebase_path_todo();
2876        struct todo_list todo_list = TODO_LIST_INIT;
2877        struct todo_item *item;
2878        struct strbuf *buf = &todo_list.buf;
2879        size_t offset = 0, commands_len = strlen(commands);
2880        int i, first;
2881
2882        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
2883                return error(_("could not read '%s'."), todo_file);
2884
2885        if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
2886                todo_list_release(&todo_list);
2887                return error(_("unusable todo list: '%s'"), todo_file);
2888        }
2889
2890        first = 1;
2891        /* insert <commands> before every pick except the first one */
2892        for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
2893                if (item->command == TODO_PICK && !first) {
2894                        strbuf_insert(buf, item->offset_in_buf + offset,
2895                                      commands, commands_len);
2896                        offset += commands_len;
2897                }
2898                first = 0;
2899        }
2900
2901        /* append final <commands> */
2902        strbuf_add(buf, commands, commands_len);
2903
2904        i = write_message(buf->buf, buf->len, todo_file, 0);
2905        todo_list_release(&todo_list);
2906        return i;
2907}
2908
2909int transform_todos(unsigned flags)
2910{
2911        const char *todo_file = rebase_path_todo();
2912        struct todo_list todo_list = TODO_LIST_INIT;
2913        struct strbuf buf = STRBUF_INIT;
2914        struct todo_item *item;
2915        int i;
2916
2917        if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
2918                return error(_("could not read '%s'."), todo_file);
2919
2920        if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
2921                todo_list_release(&todo_list);
2922                return error(_("unusable todo list: '%s'"), todo_file);
2923        }
2924
2925        for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
2926                /* if the item is not a command write it and continue */
2927                if (item->command >= TODO_COMMENT) {
2928                        strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
2929                        continue;
2930                }
2931
2932                /* add command to the buffer */
2933                if (flags & TODO_LIST_ABBREVIATE_CMDS)
2934                        strbuf_addch(&buf, command_to_char(item->command));
2935                else
2936                        strbuf_addstr(&buf, command_to_string(item->command));
2937
2938                /* add commit id */
2939                if (item->commit) {
2940                        const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
2941                                          short_commit_name(item->commit) :
2942                                          oid_to_hex(&item->commit->object.oid);
2943
2944                        if (item->command == TODO_MERGE)
2945                                strbuf_addstr(&buf, " -C");
2946                        else if (item->command == TODO_MERGE_AND_EDIT)
2947                                strbuf_addstr(&buf, " -c");
2948
2949                        strbuf_addf(&buf, " %s", oid);
2950                }
2951
2952                /* add all the rest */
2953                if (!item->arg_len)
2954                        strbuf_addch(&buf, '\n');
2955                else
2956                        strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
2957        }
2958
2959        i = write_message(buf.buf, buf.len, todo_file, 0);
2960        todo_list_release(&todo_list);
2961        return i;
2962}
2963
2964enum check_level {
2965        CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
2966};
2967
2968static enum check_level get_missing_commit_check_level(void)
2969{
2970        const char *value;
2971
2972        if (git_config_get_value("rebase.missingcommitscheck", &value) ||
2973                        !strcasecmp("ignore", value))
2974                return CHECK_IGNORE;
2975        if (!strcasecmp("warn", value))
2976                return CHECK_WARN;
2977        if (!strcasecmp("error", value))
2978                return CHECK_ERROR;
2979        warning(_("unrecognized setting %s for option "
2980                  "rebase.missingCommitsCheck. Ignoring."), value);
2981        return CHECK_IGNORE;
2982}
2983
2984/*
2985 * Check if the user dropped some commits by mistake
2986 * Behaviour determined by rebase.missingCommitsCheck.
2987 * Check if there is an unrecognized command or a
2988 * bad SHA-1 in a command.
2989 */
2990int check_todo_list(void)
2991{
2992        enum check_level check_level = get_missing_commit_check_level();
2993        struct strbuf todo_file = STRBUF_INIT;
2994        struct todo_list todo_list = TODO_LIST_INIT;
2995        struct strbuf missing = STRBUF_INIT;
2996        int advise_to_edit_todo = 0, res = 0, fd, i;
2997
2998        strbuf_addstr(&todo_file, rebase_path_todo());
2999        fd = open(todo_file.buf, O_RDONLY);
3000        if (fd < 0) {
3001                res = error_errno(_("could not open '%s'"), todo_file.buf);
3002                goto leave_check;
3003        }
3004        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3005                close(fd);
3006                res = error(_("could not read '%s'."), todo_file.buf);
3007                goto leave_check;
3008        }
3009        close(fd);
3010        advise_to_edit_todo = res =
3011                parse_insn_buffer(todo_list.buf.buf, &todo_list);
3012
3013        if (res || check_level == CHECK_IGNORE)
3014                goto leave_check;
3015
3016        /* Mark the commits in git-rebase-todo as seen */
3017        for (i = 0; i < todo_list.nr; i++) {
3018                struct commit *commit = todo_list.items[i].commit;
3019                if (commit)
3020                        commit->util = (void *)1;
3021        }
3022
3023        todo_list_release(&todo_list);
3024        strbuf_addstr(&todo_file, ".backup");
3025        fd = open(todo_file.buf, O_RDONLY);
3026        if (fd < 0) {
3027                res = error_errno(_("could not open '%s'"), todo_file.buf);
3028                goto leave_check;
3029        }
3030        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3031                close(fd);
3032                res = error(_("could not read '%s'."), todo_file.buf);
3033                goto leave_check;
3034        }
3035        close(fd);
3036        strbuf_release(&todo_file);
3037        res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3038
3039        /* Find commits in git-rebase-todo.backup yet unseen */
3040        for (i = todo_list.nr - 1; i >= 0; i--) {
3041                struct todo_item *item = todo_list.items + i;
3042                struct commit *commit = item->commit;
3043                if (commit && !commit->util) {
3044                        strbuf_addf(&missing, " - %s %.*s\n",
3045                                    short_commit_name(commit),
3046                                    item->arg_len, item->arg);
3047                        commit->util = (void *)1;
3048                }
3049        }
3050
3051        /* Warn about missing commits */
3052        if (!missing.len)
3053                goto leave_check;
3054
3055        if (check_level == CHECK_ERROR)
3056                advise_to_edit_todo = res = 1;
3057
3058        fprintf(stderr,
3059                _("Warning: some commits may have been dropped accidentally.\n"
3060                "Dropped commits (newer to older):\n"));
3061
3062        /* Make the list user-friendly and display */
3063        fputs(missing.buf, stderr);
3064        strbuf_release(&missing);
3065
3066        fprintf(stderr, _("To avoid this message, use \"drop\" to "
3067                "explicitly remove a commit.\n\n"
3068                "Use 'git config rebase.missingCommitsCheck' to change "
3069                "the level of warnings.\n"
3070                "The possible behaviours are: ignore, warn, error.\n\n"));
3071
3072leave_check:
3073        strbuf_release(&todo_file);
3074        todo_list_release(&todo_list);
3075
3076        if (advise_to_edit_todo)
3077                fprintf(stderr,
3078                        _("You can fix this with 'git rebase --edit-todo' "
3079                          "and then run 'git rebase --continue'.\n"
3080                          "Or you can abort the rebase with 'git rebase"
3081                          " --abort'.\n"));
3082
3083        return res;
3084}
3085
3086static int rewrite_file(const char *path, const char *buf, size_t len)
3087{
3088        int rc = 0;
3089        int fd = open(path, O_WRONLY | O_TRUNC);
3090        if (fd < 0)
3091                return error_errno(_("could not open '%s' for writing"), path);
3092        if (write_in_full(fd, buf, len) < 0)
3093                rc = error_errno(_("could not write to '%s'"), path);
3094        if (close(fd) && !rc)
3095                rc = error_errno(_("could not close '%s'"), path);
3096        return rc;
3097}
3098
3099/* skip picking commits whose parents are unchanged */
3100int skip_unnecessary_picks(void)
3101{
3102        const char *todo_file = rebase_path_todo();
3103        struct strbuf buf = STRBUF_INIT;
3104        struct todo_list todo_list = TODO_LIST_INIT;
3105        struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3106        int fd, i;
3107
3108        if (!read_oneliner(&buf, rebase_path_onto(), 0))
3109                return error(_("could not read 'onto'"));
3110        if (get_oid(buf.buf, &onto_oid)) {
3111                strbuf_release(&buf);
3112                return error(_("need a HEAD to fixup"));
3113        }
3114        strbuf_release(&buf);
3115
3116        fd = open(todo_file, O_RDONLY);
3117        if (fd < 0) {
3118                return error_errno(_("could not open '%s'"), todo_file);
3119        }
3120        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3121                close(fd);
3122                return error(_("could not read '%s'."), todo_file);
3123        }
3124        close(fd);
3125        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3126                todo_list_release(&todo_list);
3127                return -1;
3128        }
3129
3130        for (i = 0; i < todo_list.nr; i++) {
3131                struct todo_item *item = todo_list.items + i;
3132
3133                if (item->command >= TODO_NOOP)
3134                        continue;
3135                if (item->command != TODO_PICK)
3136                        break;
3137                if (parse_commit(item->commit)) {
3138                        todo_list_release(&todo_list);
3139                        return error(_("could not parse commit '%s'"),
3140                                oid_to_hex(&item->commit->object.oid));
3141                }
3142                if (!item->commit->parents)
3143                        break; /* root commit */
3144                if (item->commit->parents->next)
3145                        break; /* merge commit */
3146                parent_oid = &item->commit->parents->item->object.oid;
3147                if (hashcmp(parent_oid->hash, oid->hash))
3148                        break;
3149                oid = &item->commit->object.oid;
3150        }
3151        if (i > 0) {
3152                int offset = i < todo_list.nr ?
3153                        todo_list.items[i].offset_in_buf : todo_list.buf.len;
3154                const char *done_path = rebase_path_done();
3155
3156                fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3157                if (fd < 0) {
3158                        error_errno(_("could not open '%s' for writing"),
3159                                    done_path);
3160                        todo_list_release(&todo_list);
3161                        return -1;
3162                }
3163                if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3164                        error_errno(_("could not write to '%s'"), done_path);
3165                        todo_list_release(&todo_list);
3166                        close(fd);
3167                        return -1;
3168                }
3169                close(fd);
3170
3171                if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3172                                 todo_list.buf.len - offset) < 0) {
3173                        todo_list_release(&todo_list);
3174                        return -1;
3175                }
3176
3177                todo_list.current = i;
3178                if (is_fixup(peek_command(&todo_list, 0)))
3179                        record_in_rewritten(oid, peek_command(&todo_list, 0));
3180        }
3181
3182        todo_list_release(&todo_list);
3183        printf("%s\n", oid_to_hex(oid));
3184
3185        return 0;
3186}
3187
3188struct subject2item_entry {
3189        struct hashmap_entry entry;
3190        int i;
3191        char subject[FLEX_ARRAY];
3192};
3193
3194static int subject2item_cmp(const void *fndata,
3195                            const struct subject2item_entry *a,
3196                            const struct subject2item_entry *b, const void *key)
3197{
3198        return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3199}
3200
3201/*
3202 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3203 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3204 * after the former, and change "pick" to "fixup"/"squash".
3205 *
3206 * Note that if the config has specified a custom instruction format, each log
3207 * message will have to be retrieved from the commit (as the oneline in the
3208 * script cannot be trusted) in order to normalize the autosquash arrangement.
3209 */
3210int rearrange_squash(void)
3211{
3212        const char *todo_file = rebase_path_todo();
3213        struct todo_list todo_list = TODO_LIST_INIT;
3214        struct hashmap subject2item;
3215        int res = 0, rearranged = 0, *next, *tail, fd, i;
3216        char **subjects;
3217
3218        fd = open(todo_file, O_RDONLY);
3219        if (fd < 0)
3220                return error_errno(_("could not open '%s'"), todo_file);
3221        if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3222                close(fd);
3223                return error(_("could not read '%s'."), todo_file);
3224        }
3225        close(fd);
3226        if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3227                todo_list_release(&todo_list);
3228                return -1;
3229        }
3230
3231        /*
3232         * The hashmap maps onelines to the respective todo list index.
3233         *
3234         * If any items need to be rearranged, the next[i] value will indicate
3235         * which item was moved directly after the i'th.
3236         *
3237         * In that case, last[i] will indicate the index of the latest item to
3238         * be moved to appear after the i'th.
3239         */
3240        hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3241                     NULL, todo_list.nr);
3242        ALLOC_ARRAY(next, todo_list.nr);
3243        ALLOC_ARRAY(tail, todo_list.nr);
3244        ALLOC_ARRAY(subjects, todo_list.nr);
3245        for (i = 0; i < todo_list.nr; i++) {
3246                struct strbuf buf = STRBUF_INIT;
3247                struct todo_item *item = todo_list.items + i;
3248                const char *commit_buffer, *subject, *p;
3249                size_t subject_len;
3250                int i2 = -1;
3251                struct subject2item_entry *entry;
3252
3253                next[i] = tail[i] = -1;
3254                if (!item->commit || item->command == TODO_DROP) {
3255                        subjects[i] = NULL;
3256                        continue;
3257                }
3258
3259                if (is_fixup(item->command)) {
3260                        todo_list_release(&todo_list);
3261                        return error(_("the script was already rearranged."));
3262                }
3263
3264                item->commit->util = item;
3265
3266                parse_commit(item->commit);
3267                commit_buffer = get_commit_buffer(item->commit, NULL);
3268                find_commit_subject(commit_buffer, &subject);
3269                format_subject(&buf, subject, " ");
3270                subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3271                unuse_commit_buffer(item->commit, commit_buffer);
3272                if ((skip_prefix(subject, "fixup! ", &p) ||
3273                     skip_prefix(subject, "squash! ", &p))) {
3274                        struct commit *commit2;
3275
3276                        for (;;) {
3277                                while (isspace(*p))
3278                                        p++;
3279                                if (!skip_prefix(p, "fixup! ", &p) &&
3280                                    !skip_prefix(p, "squash! ", &p))
3281                                        break;
3282                        }
3283
3284                        if ((entry = hashmap_get_from_hash(&subject2item,
3285                                                           strhash(p), p)))
3286                                /* found by title */
3287                                i2 = entry->i;
3288                        else if (!strchr(p, ' ') &&
3289                                 (commit2 =
3290                                  lookup_commit_reference_by_name(p)) &&
3291                                 commit2->util)
3292                                /* found by commit name */
3293                                i2 = (struct todo_item *)commit2->util
3294                                        - todo_list.items;
3295                        else {
3296                                /* copy can be a prefix of the commit subject */
3297                                for (i2 = 0; i2 < i; i2++)
3298                                        if (subjects[i2] &&
3299                                            starts_with(subjects[i2], p))
3300                                                break;
3301                                if (i2 == i)
3302                                        i2 = -1;
3303                        }
3304                }
3305                if (i2 >= 0) {
3306                        rearranged = 1;
3307                        todo_list.items[i].command =
3308                                starts_with(subject, "fixup!") ?
3309                                TODO_FIXUP : TODO_SQUASH;
3310                        if (next[i2] < 0)
3311                                next[i2] = i;
3312                        else
3313                                next[tail[i2]] = i;
3314                        tail[i2] = i;
3315                } else if (!hashmap_get_from_hash(&subject2item,
3316                                                strhash(subject), subject)) {
3317                        FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3318                        entry->i = i;
3319                        hashmap_entry_init(entry, strhash(entry->subject));
3320                        hashmap_put(&subject2item, entry);
3321                }
3322        }
3323
3324        if (rearranged) {
3325                struct strbuf buf = STRBUF_INIT;
3326
3327                for (i = 0; i < todo_list.nr; i++) {
3328                        enum todo_command command = todo_list.items[i].command;
3329                        int cur = i;
3330
3331                        /*
3332                         * Initially, all commands are 'pick's. If it is a
3333                         * fixup or a squash now, we have rearranged it.
3334                         */
3335                        if (is_fixup(command))
3336                                continue;
3337
3338                        while (cur >= 0) {
3339                                int offset = todo_list.items[cur].offset_in_buf;
3340                                int end_offset = cur + 1 < todo_list.nr ?
3341                                        todo_list.items[cur + 1].offset_in_buf :
3342                                        todo_list.buf.len;
3343                                char *bol = todo_list.buf.buf + offset;
3344                                char *eol = todo_list.buf.buf + end_offset;
3345
3346                                /* replace 'pick', by 'fixup' or 'squash' */
3347                                command = todo_list.items[cur].command;
3348                                if (is_fixup(command)) {
3349                                        strbuf_addstr(&buf,
3350                                                todo_command_info[command].str);
3351                                        bol += strcspn(bol, " \t");
3352                                }
3353
3354                                strbuf_add(&buf, bol, eol - bol);
3355
3356                                cur = next[cur];
3357                        }
3358                }
3359
3360                res = rewrite_file(todo_file, buf.buf, buf.len);
3361                strbuf_release(&buf);
3362        }
3363
3364        free(next);
3365        free(tail);
3366        for (i = 0; i < todo_list.nr; i++)
3367                free(subjects[i]);
3368        free(subjects);
3369        hashmap_free(&subject2item, 1);
3370        todo_list_release(&todo_list);
3371
3372        return res;
3373}