84534ee05794fb2b99942aa9c33362170ca00c67
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "sequencer.h"
   4#include "dir.h"
   5#include "object.h"
   6#include "commit.h"
   7#include "tag.h"
   8#include "run-command.h"
   9#include "exec_cmd.h"
  10#include "utf8.h"
  11#include "cache-tree.h"
  12#include "diff.h"
  13#include "revision.h"
  14#include "rerere.h"
  15#include "merge-recursive.h"
  16#include "refs.h"
  17#include "argv-array.h"
  18#include "quote.h"
  19#include "trailer.h"
  20#include "log-tree.h"
  21#include "wt-status.h"
  22
  23#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  24
  25const char sign_off_header[] = "Signed-off-by: ";
  26static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  27
  28GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  29
  30static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  31static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  32static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  33static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  34
  35static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  36/*
  37 * The file containing rebase commands, comments, and empty lines.
  38 * This file is created by "git rebase -i" then edited by the user. As
  39 * the lines are processed, they are removed from the front of this
  40 * file and written to the tail of 'done'.
  41 */
  42static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  43/*
  44 * The rebase command lines that have already been processed. A line
  45 * is moved here when it is first handled, before any associated user
  46 * actions.
  47 */
  48static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  49/*
  50 * The commit message that is planned to be used for any changes that
  51 * need to be committed following a user interaction.
  52 */
  53static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  54/*
  55 * The file into which is accumulated the suggested commit message for
  56 * squash/fixup commands. When the first of a series of squash/fixups
  57 * is seen, the file is created and the commit message from the
  58 * previous commit and from the first squash/fixup commit are written
  59 * to it. The commit message for each subsequent squash/fixup commit
  60 * is appended to the file as it is processed.
  61 *
  62 * The first line of the file is of the form
  63 *     # This is a combination of $count commits.
  64 * where $count is the number of commits whose messages have been
  65 * written to the file so far (including the initial "pick" commit).
  66 * Each time that a commit message is processed, this line is read and
  67 * updated. It is deleted just before the combined commit is made.
  68 */
  69static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
  70/*
  71 * If the current series of squash/fixups has not yet included a squash
  72 * command, then this file exists and holds the commit message of the
  73 * original "pick" commit.  (If the series ends without a "squash"
  74 * command, then this can be used as the commit message of the combined
  75 * commit without opening the editor.)
  76 */
  77static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
  78/*
  79 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  80 * GIT_AUTHOR_DATE that will be used for the commit that is currently
  81 * being rebased.
  82 */
  83static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  84/*
  85 * When an "edit" rebase command is being processed, the SHA1 of the
  86 * commit to be edited is recorded in this file.  When "git rebase
  87 * --continue" is executed, if there are any staged changes then they
  88 * will be amended to the HEAD commit, but only provided the HEAD
  89 * commit is still the commit to be edited.  When any other rebase
  90 * command is processed, this file is deleted.
  91 */
  92static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
  93/*
  94 * When we stop at a given patch via the "edit" command, this file contains
  95 * the abbreviated commit name of the corresponding patch.
  96 */
  97static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
  98/*
  99 * For the post-rewrite hook, we make a list of rewritten commits and
 100 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 101 * commits that have been processed, but not committed yet,
 102 * e.g. because they are waiting for a 'squash' command.
 103 */
 104static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
 105static GIT_PATH_FUNC(rebase_path_rewritten_pending,
 106        "rebase-merge/rewritten-pending")
 107/*
 108 * The following files are written by git-rebase just after parsing the
 109 * command-line (and are only consumed, not modified, by the sequencer).
 110 */
 111static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
 112static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
 113static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
 114static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
 115static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
 116static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
 117static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
 118static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
 119
 120static inline int is_rebase_i(const struct replay_opts *opts)
 121{
 122        return opts->action == REPLAY_INTERACTIVE_REBASE;
 123}
 124
 125static const char *get_dir(const struct replay_opts *opts)
 126{
 127        if (is_rebase_i(opts))
 128                return rebase_path();
 129        return git_path_seq_dir();
 130}
 131
 132static const char *get_todo_path(const struct replay_opts *opts)
 133{
 134        if (is_rebase_i(opts))
 135                return rebase_path_todo();
 136        return git_path_todo_file();
 137}
 138
 139/*
 140 * Returns 0 for non-conforming footer
 141 * Returns 1 for conforming footer
 142 * Returns 2 when sob exists within conforming footer
 143 * Returns 3 when sob exists within conforming footer as last entry
 144 */
 145static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
 146        int ignore_footer)
 147{
 148        struct trailer_info info;
 149        int i;
 150        int found_sob = 0, found_sob_last = 0;
 151
 152        trailer_info_get(&info, sb->buf);
 153
 154        if (info.trailer_start == info.trailer_end)
 155                return 0;
 156
 157        for (i = 0; i < info.trailer_nr; i++)
 158                if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
 159                        found_sob = 1;
 160                        if (i == info.trailer_nr - 1)
 161                                found_sob_last = 1;
 162                }
 163
 164        trailer_info_release(&info);
 165
 166        if (found_sob_last)
 167                return 3;
 168        if (found_sob)
 169                return 2;
 170        return 1;
 171}
 172
 173static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
 174{
 175        static struct strbuf buf = STRBUF_INIT;
 176
 177        strbuf_reset(&buf);
 178        if (opts->gpg_sign)
 179                sq_quotef(&buf, "-S%s", opts->gpg_sign);
 180        return buf.buf;
 181}
 182
 183int sequencer_remove_state(struct replay_opts *opts)
 184{
 185        struct strbuf dir = STRBUF_INIT;
 186        int i;
 187
 188        free(opts->gpg_sign);
 189        free(opts->strategy);
 190        for (i = 0; i < opts->xopts_nr; i++)
 191                free(opts->xopts[i]);
 192        free(opts->xopts);
 193
 194        strbuf_addf(&dir, "%s", get_dir(opts));
 195        remove_dir_recursively(&dir, 0);
 196        strbuf_release(&dir);
 197
 198        return 0;
 199}
 200
 201static const char *action_name(const struct replay_opts *opts)
 202{
 203        switch (opts->action) {
 204        case REPLAY_REVERT:
 205                return N_("revert");
 206        case REPLAY_PICK:
 207                return N_("cherry-pick");
 208        case REPLAY_INTERACTIVE_REBASE:
 209                return N_("rebase -i");
 210        }
 211        die(_("Unknown action: %d"), opts->action);
 212}
 213
 214struct commit_message {
 215        char *parent_label;
 216        char *label;
 217        char *subject;
 218        const char *message;
 219};
 220
 221static const char *short_commit_name(struct commit *commit)
 222{
 223        return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 224}
 225
 226static int get_message(struct commit *commit, struct commit_message *out)
 227{
 228        const char *abbrev, *subject;
 229        int subject_len;
 230
 231        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 232        abbrev = short_commit_name(commit);
 233
 234        subject_len = find_commit_subject(out->message, &subject);
 235
 236        out->subject = xmemdupz(subject, subject_len);
 237        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 238        out->parent_label = xstrfmt("parent of %s", out->label);
 239
 240        return 0;
 241}
 242
 243static void free_message(struct commit *commit, struct commit_message *msg)
 244{
 245        free(msg->parent_label);
 246        free(msg->label);
 247        free(msg->subject);
 248        unuse_commit_buffer(commit, msg->message);
 249}
 250
 251static void print_advice(int show_hint, struct replay_opts *opts)
 252{
 253        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 254
 255        if (msg) {
 256                fprintf(stderr, "%s\n", msg);
 257                /*
 258                 * A conflict has occurred but the porcelain
 259                 * (typically rebase --interactive) wants to take care
 260                 * of the commit itself so remove CHERRY_PICK_HEAD
 261                 */
 262                unlink(git_path_cherry_pick_head());
 263                return;
 264        }
 265
 266        if (show_hint) {
 267                if (opts->no_commit)
 268                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 269                                 "with 'git add <paths>' or 'git rm <paths>'"));
 270                else
 271                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 272                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 273                                 "and commit the result with 'git commit'"));
 274        }
 275}
 276
 277static int write_message(const void *buf, size_t len, const char *filename,
 278                         int append_eol)
 279{
 280        static struct lock_file msg_file;
 281
 282        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 283        if (msg_fd < 0)
 284                return error_errno(_("could not lock '%s'"), filename);
 285        if (write_in_full(msg_fd, buf, len) < 0) {
 286                rollback_lock_file(&msg_file);
 287                return error_errno(_("could not write to '%s'"), filename);
 288        }
 289        if (append_eol && write(msg_fd, "\n", 1) < 0) {
 290                rollback_lock_file(&msg_file);
 291                return error_errno(_("could not write eol to '%s'"), filename);
 292        }
 293        if (commit_lock_file(&msg_file) < 0) {
 294                rollback_lock_file(&msg_file);
 295                return error(_("failed to finalize '%s'."), filename);
 296        }
 297
 298        return 0;
 299}
 300
 301/*
 302 * Reads a file that was presumably written by a shell script, i.e. with an
 303 * end-of-line marker that needs to be stripped.
 304 *
 305 * Note that only the last end-of-line marker is stripped, consistent with the
 306 * behavior of "$(cat path)" in a shell script.
 307 *
 308 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 309 */
 310static int read_oneliner(struct strbuf *buf,
 311        const char *path, int skip_if_empty)
 312{
 313        int orig_len = buf->len;
 314
 315        if (!file_exists(path))
 316                return 0;
 317
 318        if (strbuf_read_file(buf, path, 0) < 0) {
 319                warning_errno(_("could not read '%s'"), path);
 320                return 0;
 321        }
 322
 323        if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
 324                if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
 325                        --buf->len;
 326                buf->buf[buf->len] = '\0';
 327        }
 328
 329        if (skip_if_empty && buf->len == orig_len)
 330                return 0;
 331
 332        return 1;
 333}
 334
 335static struct tree *empty_tree(void)
 336{
 337        return lookup_tree(EMPTY_TREE_SHA1_BIN);
 338}
 339
 340static int error_dirty_index(struct replay_opts *opts)
 341{
 342        if (read_cache_unmerged())
 343                return error_resolve_conflict(_(action_name(opts)));
 344
 345        error(_("your local changes would be overwritten by %s."),
 346                _(action_name(opts)));
 347
 348        if (advice_commit_before_merge)
 349                advise(_("commit your changes or stash them to proceed."));
 350        return -1;
 351}
 352
 353static void update_abort_safety_file(void)
 354{
 355        struct object_id head;
 356
 357        /* Do nothing on a single-pick */
 358        if (!file_exists(git_path_seq_dir()))
 359                return;
 360
 361        if (!get_oid("HEAD", &head))
 362                write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
 363        else
 364                write_file(git_path_abort_safety_file(), "%s", "");
 365}
 366
 367static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 368                        int unborn, struct replay_opts *opts)
 369{
 370        struct ref_transaction *transaction;
 371        struct strbuf sb = STRBUF_INIT;
 372        struct strbuf err = STRBUF_INIT;
 373
 374        read_cache();
 375        if (checkout_fast_forward(from, to, 1))
 376                return -1; /* the callee should have complained already */
 377
 378        strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
 379
 380        transaction = ref_transaction_begin(&err);
 381        if (!transaction ||
 382            ref_transaction_update(transaction, "HEAD",
 383                                   to, unborn ? null_sha1 : from,
 384                                   0, sb.buf, &err) ||
 385            ref_transaction_commit(transaction, &err)) {
 386                ref_transaction_free(transaction);
 387                error("%s", err.buf);
 388                strbuf_release(&sb);
 389                strbuf_release(&err);
 390                return -1;
 391        }
 392
 393        strbuf_release(&sb);
 394        strbuf_release(&err);
 395        ref_transaction_free(transaction);
 396        update_abort_safety_file();
 397        return 0;
 398}
 399
 400void append_conflicts_hint(struct strbuf *msgbuf)
 401{
 402        int i;
 403
 404        strbuf_addch(msgbuf, '\n');
 405        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 406        for (i = 0; i < active_nr;) {
 407                const struct cache_entry *ce = active_cache[i++];
 408                if (ce_stage(ce)) {
 409                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 410                        while (i < active_nr && !strcmp(ce->name,
 411                                                        active_cache[i]->name))
 412                                i++;
 413                }
 414        }
 415}
 416
 417static int do_recursive_merge(struct commit *base, struct commit *next,
 418                              const char *base_label, const char *next_label,
 419                              unsigned char *head, struct strbuf *msgbuf,
 420                              struct replay_opts *opts)
 421{
 422        struct merge_options o;
 423        struct tree *result, *next_tree, *base_tree, *head_tree;
 424        int clean;
 425        char **xopt;
 426        static struct lock_file index_lock;
 427
 428        hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
 429
 430        read_cache();
 431
 432        init_merge_options(&o);
 433        o.ancestor = base ? base_label : "(empty tree)";
 434        o.branch1 = "HEAD";
 435        o.branch2 = next ? next_label : "(empty tree)";
 436
 437        head_tree = parse_tree_indirect(head);
 438        next_tree = next ? next->tree : empty_tree();
 439        base_tree = base ? base->tree : empty_tree();
 440
 441        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 442                parse_merge_opt(&o, *xopt);
 443
 444        clean = merge_trees(&o,
 445                            head_tree,
 446                            next_tree, base_tree, &result);
 447        strbuf_release(&o.obuf);
 448        if (clean < 0)
 449                return clean;
 450
 451        if (active_cache_changed &&
 452            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 453                /* TRANSLATORS: %s will be "revert", "cherry-pick" or
 454                 * "rebase -i".
 455                 */
 456                return error(_("%s: Unable to write new index file"),
 457                        _(action_name(opts)));
 458        rollback_lock_file(&index_lock);
 459
 460        if (opts->signoff)
 461                append_signoff(msgbuf, 0, 0);
 462
 463        if (!clean)
 464                append_conflicts_hint(msgbuf);
 465
 466        return !clean;
 467}
 468
 469static int is_index_unchanged(void)
 470{
 471        unsigned char head_sha1[20];
 472        struct commit *head_commit;
 473
 474        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
 475                return error(_("could not resolve HEAD commit\n"));
 476
 477        head_commit = lookup_commit(head_sha1);
 478
 479        /*
 480         * If head_commit is NULL, check_commit, called from
 481         * lookup_commit, would have indicated that head_commit is not
 482         * a commit object already.  parse_commit() will return failure
 483         * without further complaints in such a case.  Otherwise, if
 484         * the commit is invalid, parse_commit() will complain.  So
 485         * there is nothing for us to say here.  Just return failure.
 486         */
 487        if (parse_commit(head_commit))
 488                return -1;
 489
 490        if (!active_cache_tree)
 491                active_cache_tree = cache_tree();
 492
 493        if (!cache_tree_fully_valid(active_cache_tree))
 494                if (cache_tree_update(&the_index, 0))
 495                        return error(_("unable to update cache tree\n"));
 496
 497        return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
 498}
 499
 500static int write_author_script(const char *message)
 501{
 502        struct strbuf buf = STRBUF_INIT;
 503        const char *eol;
 504        int res;
 505
 506        for (;;)
 507                if (!*message || starts_with(message, "\n")) {
 508missing_author:
 509                        /* Missing 'author' line? */
 510                        unlink(rebase_path_author_script());
 511                        return 0;
 512                } else if (skip_prefix(message, "author ", &message))
 513                        break;
 514                else if ((eol = strchr(message, '\n')))
 515                        message = eol + 1;
 516                else
 517                        goto missing_author;
 518
 519        strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
 520        while (*message && *message != '\n' && *message != '\r')
 521                if (skip_prefix(message, " <", &message))
 522                        break;
 523                else if (*message != '\'')
 524                        strbuf_addch(&buf, *(message++));
 525                else
 526                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 527        strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
 528        while (*message && *message != '\n' && *message != '\r')
 529                if (skip_prefix(message, "> ", &message))
 530                        break;
 531                else if (*message != '\'')
 532                        strbuf_addch(&buf, *(message++));
 533                else
 534                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 535        strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
 536        while (*message && *message != '\n' && *message != '\r')
 537                if (*message != '\'')
 538                        strbuf_addch(&buf, *(message++));
 539                else
 540                        strbuf_addf(&buf, "'\\\\%c'", *(message++));
 541        res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
 542        strbuf_release(&buf);
 543        return res;
 544}
 545
 546/*
 547 * Read a list of environment variable assignments (such as the author-script
 548 * file) into an environment block. Returns -1 on error, 0 otherwise.
 549 */
 550static int read_env_script(struct argv_array *env)
 551{
 552        struct strbuf script = STRBUF_INIT;
 553        int i, count = 0;
 554        char *p, *p2;
 555
 556        if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
 557                return -1;
 558
 559        for (p = script.buf; *p; p++)
 560                if (skip_prefix(p, "'\\\\''", (const char **)&p2))
 561                        strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
 562                else if (*p == '\'')
 563                        strbuf_splice(&script, p-- - script.buf, 1, "", 0);
 564                else if (*p == '\n') {
 565                        *p = '\0';
 566                        count++;
 567                }
 568
 569        for (i = 0, p = script.buf; i < count; i++) {
 570                argv_array_push(env, p);
 571                p += strlen(p) + 1;
 572        }
 573
 574        return 0;
 575}
 576
 577static const char staged_changes_advice[] =
 578N_("you have staged changes in your working tree\n"
 579"If these changes are meant to be squashed into the previous commit, run:\n"
 580"\n"
 581"  git commit --amend %s\n"
 582"\n"
 583"If they are meant to go into a new commit, run:\n"
 584"\n"
 585"  git commit %s\n"
 586"\n"
 587"In both cases, once you're done, continue with:\n"
 588"\n"
 589"  git rebase --continue\n");
 590
 591/*
 592 * If we are cherry-pick, and if the merge did not result in
 593 * hand-editing, we will hit this commit and inherit the original
 594 * author date and name.
 595 *
 596 * If we are revert, or if our cherry-pick results in a hand merge,
 597 * we had better say that the current user is responsible for that.
 598 *
 599 * An exception is when run_git_commit() is called during an
 600 * interactive rebase: in that case, we will want to retain the
 601 * author metadata.
 602 */
 603static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 604                          int allow_empty, int edit, int amend,
 605                          int cleanup_commit_message)
 606{
 607        struct child_process cmd = CHILD_PROCESS_INIT;
 608        const char *value;
 609
 610        cmd.git_cmd = 1;
 611
 612        if (is_rebase_i(opts)) {
 613                if (!edit) {
 614                        cmd.stdout_to_stderr = 1;
 615                        cmd.err = -1;
 616                }
 617
 618                if (read_env_script(&cmd.env_array)) {
 619                        const char *gpg_opt = gpg_sign_opt_quoted(opts);
 620
 621                        return error(_(staged_changes_advice),
 622                                     gpg_opt, gpg_opt);
 623                }
 624        }
 625
 626        argv_array_push(&cmd.args, "commit");
 627        argv_array_push(&cmd.args, "-n");
 628
 629        if (amend)
 630                argv_array_push(&cmd.args, "--amend");
 631        if (opts->gpg_sign)
 632                argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
 633        if (opts->signoff)
 634                argv_array_push(&cmd.args, "-s");
 635        if (defmsg)
 636                argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
 637        if (cleanup_commit_message)
 638                argv_array_push(&cmd.args, "--cleanup=strip");
 639        if (edit)
 640                argv_array_push(&cmd.args, "-e");
 641        else if (!cleanup_commit_message &&
 642                 !opts->signoff && !opts->record_origin &&
 643                 git_config_get_value("commit.cleanup", &value))
 644                argv_array_push(&cmd.args, "--cleanup=verbatim");
 645
 646        if (allow_empty)
 647                argv_array_push(&cmd.args, "--allow-empty");
 648
 649        if (opts->allow_empty_message)
 650                argv_array_push(&cmd.args, "--allow-empty-message");
 651
 652        if (cmd.err == -1) {
 653                /* hide stderr on success */
 654                struct strbuf buf = STRBUF_INIT;
 655                int rc = pipe_command(&cmd,
 656                                      NULL, 0,
 657                                      /* stdout is already redirected */
 658                                      NULL, 0,
 659                                      &buf, 0);
 660                if (rc)
 661                        fputs(buf.buf, stderr);
 662                strbuf_release(&buf);
 663                return rc;
 664        }
 665
 666        return run_command(&cmd);
 667}
 668
 669static int is_original_commit_empty(struct commit *commit)
 670{
 671        const unsigned char *ptree_sha1;
 672
 673        if (parse_commit(commit))
 674                return error(_("could not parse commit %s\n"),
 675                             oid_to_hex(&commit->object.oid));
 676        if (commit->parents) {
 677                struct commit *parent = commit->parents->item;
 678                if (parse_commit(parent))
 679                        return error(_("could not parse parent commit %s\n"),
 680                                oid_to_hex(&parent->object.oid));
 681                ptree_sha1 = parent->tree->object.oid.hash;
 682        } else {
 683                ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
 684        }
 685
 686        return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
 687}
 688
 689/*
 690 * Do we run "git commit" with "--allow-empty"?
 691 */
 692static int allow_empty(struct replay_opts *opts, struct commit *commit)
 693{
 694        int index_unchanged, empty_commit;
 695
 696        /*
 697         * Three cases:
 698         *
 699         * (1) we do not allow empty at all and error out.
 700         *
 701         * (2) we allow ones that were initially empty, but
 702         * forbid the ones that become empty;
 703         *
 704         * (3) we allow both.
 705         */
 706        if (!opts->allow_empty)
 707                return 0; /* let "git commit" barf as necessary */
 708
 709        index_unchanged = is_index_unchanged();
 710        if (index_unchanged < 0)
 711                return index_unchanged;
 712        if (!index_unchanged)
 713                return 0; /* we do not have to say --allow-empty */
 714
 715        if (opts->keep_redundant_commits)
 716                return 1;
 717
 718        empty_commit = is_original_commit_empty(commit);
 719        if (empty_commit < 0)
 720                return empty_commit;
 721        if (!empty_commit)
 722                return 0;
 723        else
 724                return 1;
 725}
 726
 727/*
 728 * Note that ordering matters in this enum. Not only must it match the mapping
 729 * below, it is also divided into several sections that matter.  When adding
 730 * new commands, make sure you add it in the right section.
 731 */
 732enum todo_command {
 733        /* commands that handle commits */
 734        TODO_PICK = 0,
 735        TODO_REVERT,
 736        TODO_EDIT,
 737        TODO_REWORD,
 738        TODO_FIXUP,
 739        TODO_SQUASH,
 740        /* commands that do something else than handling a single commit */
 741        TODO_EXEC,
 742        /* commands that do nothing but are counted for reporting progress */
 743        TODO_NOOP,
 744        TODO_DROP,
 745        /* comments (not counted for reporting progress) */
 746        TODO_COMMENT
 747};
 748
 749static struct {
 750        char c;
 751        const char *str;
 752} todo_command_info[] = {
 753        { 'p', "pick" },
 754        { 0,   "revert" },
 755        { 'e', "edit" },
 756        { 'r', "reword" },
 757        { 'f', "fixup" },
 758        { 's', "squash" },
 759        { 'x', "exec" },
 760        { 0,   "noop" },
 761        { 'd', "drop" },
 762        { 0,   NULL }
 763};
 764
 765static const char *command_to_string(const enum todo_command command)
 766{
 767        if (command < TODO_COMMENT)
 768                return todo_command_info[command].str;
 769        die("Unknown command: %d", command);
 770}
 771
 772static int is_noop(const enum todo_command command)
 773{
 774        return TODO_NOOP <= command;
 775}
 776
 777static int is_fixup(enum todo_command command)
 778{
 779        return command == TODO_FIXUP || command == TODO_SQUASH;
 780}
 781
 782static int update_squash_messages(enum todo_command command,
 783                struct commit *commit, struct replay_opts *opts)
 784{
 785        struct strbuf buf = STRBUF_INIT;
 786        int count, res;
 787        const char *message, *body;
 788
 789        if (file_exists(rebase_path_squash_msg())) {
 790                struct strbuf header = STRBUF_INIT;
 791                char *eol, *p;
 792
 793                if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
 794                        return error(_("could not read '%s'"),
 795                                rebase_path_squash_msg());
 796
 797                p = buf.buf + 1;
 798                eol = strchrnul(buf.buf, '\n');
 799                if (buf.buf[0] != comment_line_char ||
 800                    (p += strcspn(p, "0123456789\n")) == eol)
 801                        return error(_("unexpected 1st line of squash message:"
 802                                       "\n\n\t%.*s"),
 803                                     (int)(eol - buf.buf), buf.buf);
 804                count = strtol(p, NULL, 10);
 805
 806                if (count < 1)
 807                        return error(_("invalid 1st line of squash message:\n"
 808                                       "\n\t%.*s"),
 809                                     (int)(eol - buf.buf), buf.buf);
 810
 811                strbuf_addf(&header, "%c ", comment_line_char);
 812                strbuf_addf(&header,
 813                            _("This is a combination of %d commits."), ++count);
 814                strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
 815                strbuf_release(&header);
 816        } else {
 817                unsigned char head[20];
 818                struct commit *head_commit;
 819                const char *head_message, *body;
 820
 821                if (get_sha1("HEAD", head))
 822                        return error(_("need a HEAD to fixup"));
 823                if (!(head_commit = lookup_commit_reference(head)))
 824                        return error(_("could not read HEAD"));
 825                if (!(head_message = get_commit_buffer(head_commit, NULL)))
 826                        return error(_("could not read HEAD's commit message"));
 827
 828                find_commit_subject(head_message, &body);
 829                if (write_message(body, strlen(body),
 830                                  rebase_path_fixup_msg(), 0)) {
 831                        unuse_commit_buffer(head_commit, head_message);
 832                        return error(_("cannot write '%s'"),
 833                                     rebase_path_fixup_msg());
 834                }
 835
 836                count = 2;
 837                strbuf_addf(&buf, "%c ", comment_line_char);
 838                strbuf_addf(&buf, _("This is a combination of %d commits."),
 839                            count);
 840                strbuf_addf(&buf, "\n%c ", comment_line_char);
 841                strbuf_addstr(&buf, _("This is the 1st commit message:"));
 842                strbuf_addstr(&buf, "\n\n");
 843                strbuf_addstr(&buf, body);
 844
 845                unuse_commit_buffer(head_commit, head_message);
 846        }
 847
 848        if (!(message = get_commit_buffer(commit, NULL)))
 849                return error(_("could not read commit message of %s"),
 850                             oid_to_hex(&commit->object.oid));
 851        find_commit_subject(message, &body);
 852
 853        if (command == TODO_SQUASH) {
 854                unlink(rebase_path_fixup_msg());
 855                strbuf_addf(&buf, "\n%c ", comment_line_char);
 856                strbuf_addf(&buf, _("This is the commit message #%d:"), count);
 857                strbuf_addstr(&buf, "\n\n");
 858                strbuf_addstr(&buf, body);
 859        } else if (command == TODO_FIXUP) {
 860                strbuf_addf(&buf, "\n%c ", comment_line_char);
 861                strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
 862                            count);
 863                strbuf_addstr(&buf, "\n\n");
 864                strbuf_add_commented_lines(&buf, body, strlen(body));
 865        } else
 866                return error(_("unknown command: %d"), command);
 867        unuse_commit_buffer(commit, message);
 868
 869        res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
 870        strbuf_release(&buf);
 871        return res;
 872}
 873
 874static void flush_rewritten_pending(void) {
 875        struct strbuf buf = STRBUF_INIT;
 876        unsigned char newsha1[20];
 877        FILE *out;
 878
 879        if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), 82) > 0 &&
 880                        !get_sha1("HEAD", newsha1) &&
 881                        (out = fopen(rebase_path_rewritten_list(), "a"))) {
 882                char *bol = buf.buf, *eol;
 883
 884                while (*bol) {
 885                        eol = strchrnul(bol, '\n');
 886                        fprintf(out, "%.*s %s\n", (int)(eol - bol),
 887                                        bol, sha1_to_hex(newsha1));
 888                        if (!*eol)
 889                                break;
 890                        bol = eol + 1;
 891                }
 892                fclose(out);
 893                unlink(rebase_path_rewritten_pending());
 894        }
 895        strbuf_release(&buf);
 896}
 897
 898static void record_in_rewritten(struct object_id *oid,
 899                enum todo_command next_command) {
 900        FILE *out = fopen(rebase_path_rewritten_pending(), "a");
 901
 902        if (!out)
 903                return;
 904
 905        fprintf(out, "%s\n", oid_to_hex(oid));
 906        fclose(out);
 907
 908        if (!is_fixup(next_command))
 909                flush_rewritten_pending();
 910}
 911
 912static int do_pick_commit(enum todo_command command, struct commit *commit,
 913                struct replay_opts *opts, int final_fixup)
 914{
 915        int edit = opts->edit, cleanup_commit_message = 0;
 916        const char *msg_file = edit ? NULL : git_path_merge_msg();
 917        unsigned char head[20];
 918        struct commit *base, *next, *parent;
 919        const char *base_label, *next_label;
 920        struct commit_message msg = { NULL, NULL, NULL, NULL };
 921        struct strbuf msgbuf = STRBUF_INIT;
 922        int res, unborn = 0, amend = 0, allow = 0;
 923
 924        if (opts->no_commit) {
 925                /*
 926                 * We do not intend to commit immediately.  We just want to
 927                 * merge the differences in, so let's compute the tree
 928                 * that represents the "current" state for merge-recursive
 929                 * to work on.
 930                 */
 931                if (write_cache_as_tree(head, 0, NULL))
 932                        return error(_("your index file is unmerged."));
 933        } else {
 934                unborn = get_sha1("HEAD", head);
 935                if (unborn)
 936                        hashcpy(head, EMPTY_TREE_SHA1_BIN);
 937                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
 938                        return error_dirty_index(opts);
 939        }
 940        discard_cache();
 941
 942        if (!commit->parents)
 943                parent = NULL;
 944        else if (commit->parents->next) {
 945                /* Reverting or cherry-picking a merge commit */
 946                int cnt;
 947                struct commit_list *p;
 948
 949                if (!opts->mainline)
 950                        return error(_("commit %s is a merge but no -m option was given."),
 951                                oid_to_hex(&commit->object.oid));
 952
 953                for (cnt = 1, p = commit->parents;
 954                     cnt != opts->mainline && p;
 955                     cnt++)
 956                        p = p->next;
 957                if (cnt != opts->mainline || !p)
 958                        return error(_("commit %s does not have parent %d"),
 959                                oid_to_hex(&commit->object.oid), opts->mainline);
 960                parent = p->item;
 961        } else if (0 < opts->mainline)
 962                return error(_("mainline was specified but commit %s is not a merge."),
 963                        oid_to_hex(&commit->object.oid));
 964        else
 965                parent = commit->parents->item;
 966
 967        if (get_message(commit, &msg) != 0)
 968                return error(_("cannot get commit message for %s"),
 969                        oid_to_hex(&commit->object.oid));
 970
 971        if (opts->allow_ff && !is_fixup(command) &&
 972            ((parent && !hashcmp(parent->object.oid.hash, head)) ||
 973             (!parent && unborn))) {
 974                if (is_rebase_i(opts))
 975                        write_author_script(msg.message);
 976                res = fast_forward_to(commit->object.oid.hash, head, unborn,
 977                        opts);
 978                if (res || command != TODO_REWORD)
 979                        goto leave;
 980                edit = amend = 1;
 981                msg_file = NULL;
 982                goto fast_forward_edit;
 983        }
 984        if (parent && parse_commit(parent) < 0)
 985                /* TRANSLATORS: The first %s will be a "todo" command like
 986                   "revert" or "pick", the second %s a SHA1. */
 987                return error(_("%s: cannot parse parent commit %s"),
 988                        command_to_string(command),
 989                        oid_to_hex(&parent->object.oid));
 990
 991        /*
 992         * "commit" is an existing commit.  We would want to apply
 993         * the difference it introduces since its first parent "prev"
 994         * on top of the current HEAD if we are cherry-pick.  Or the
 995         * reverse of it if we are revert.
 996         */
 997
 998        if (command == TODO_REVERT) {
 999                base = commit;
1000                base_label = msg.label;
1001                next = parent;
1002                next_label = msg.parent_label;
1003                strbuf_addstr(&msgbuf, "Revert \"");
1004                strbuf_addstr(&msgbuf, msg.subject);
1005                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1006                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1007
1008                if (commit->parents && commit->parents->next) {
1009                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1010                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1011                }
1012                strbuf_addstr(&msgbuf, ".\n");
1013        } else {
1014                const char *p;
1015
1016                base = parent;
1017                base_label = msg.parent_label;
1018                next = commit;
1019                next_label = msg.label;
1020
1021                /* Append the commit log message to msgbuf. */
1022                if (find_commit_subject(msg.message, &p))
1023                        strbuf_addstr(&msgbuf, p);
1024
1025                if (opts->record_origin) {
1026                        if (!has_conforming_footer(&msgbuf, NULL, 0))
1027                                strbuf_addch(&msgbuf, '\n');
1028                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
1029                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1030                        strbuf_addstr(&msgbuf, ")\n");
1031                }
1032        }
1033
1034        if (command == TODO_REWORD)
1035                edit = 1;
1036        else if (is_fixup(command)) {
1037                if (update_squash_messages(command, commit, opts))
1038                        return -1;
1039                amend = 1;
1040                if (!final_fixup)
1041                        msg_file = rebase_path_squash_msg();
1042                else if (file_exists(rebase_path_fixup_msg())) {
1043                        cleanup_commit_message = 1;
1044                        msg_file = rebase_path_fixup_msg();
1045                } else {
1046                        const char *dest = git_path("SQUASH_MSG");
1047                        unlink(dest);
1048                        if (copy_file(dest, rebase_path_squash_msg(), 0666))
1049                                return error(_("could not rename '%s' to '%s'"),
1050                                             rebase_path_squash_msg(), dest);
1051                        unlink(git_path("MERGE_MSG"));
1052                        msg_file = dest;
1053                        edit = 1;
1054                }
1055        }
1056
1057        if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1058                res = -1;
1059        else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1060                res = do_recursive_merge(base, next, base_label, next_label,
1061                                         head, &msgbuf, opts);
1062                if (res < 0)
1063                        return res;
1064                res |= write_message(msgbuf.buf, msgbuf.len,
1065                                     git_path_merge_msg(), 0);
1066        } else {
1067                struct commit_list *common = NULL;
1068                struct commit_list *remotes = NULL;
1069
1070                res = write_message(msgbuf.buf, msgbuf.len,
1071                                    git_path_merge_msg(), 0);
1072
1073                commit_list_insert(base, &common);
1074                commit_list_insert(next, &remotes);
1075                res |= try_merge_command(opts->strategy,
1076                                         opts->xopts_nr, (const char **)opts->xopts,
1077                                        common, sha1_to_hex(head), remotes);
1078                free_commit_list(common);
1079                free_commit_list(remotes);
1080        }
1081        strbuf_release(&msgbuf);
1082
1083        /*
1084         * If the merge was clean or if it failed due to conflict, we write
1085         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1086         * However, if the merge did not even start, then we don't want to
1087         * write it at all.
1088         */
1089        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1090            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
1091                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1092                res = -1;
1093        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1094            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
1095                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1096                res = -1;
1097
1098        if (res) {
1099                error(command == TODO_REVERT
1100                      ? _("could not revert %s... %s")
1101                      : _("could not apply %s... %s"),
1102                      short_commit_name(commit), msg.subject);
1103                print_advice(res == 1, opts);
1104                rerere(opts->allow_rerere_auto);
1105                goto leave;
1106        }
1107
1108        allow = allow_empty(opts, commit);
1109        if (allow < 0) {
1110                res = allow;
1111                goto leave;
1112        }
1113        if (!opts->no_commit)
1114fast_forward_edit:
1115                res = run_git_commit(msg_file, opts, allow, edit, amend,
1116                                     cleanup_commit_message);
1117
1118        if (!res && final_fixup) {
1119                unlink(rebase_path_fixup_msg());
1120                unlink(rebase_path_squash_msg());
1121        }
1122
1123leave:
1124        free_message(commit, &msg);
1125        update_abort_safety_file();
1126
1127        return res;
1128}
1129
1130static int prepare_revs(struct replay_opts *opts)
1131{
1132        /*
1133         * picking (but not reverting) ranges (but not individual revisions)
1134         * should be done in reverse
1135         */
1136        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1137                opts->revs->reverse ^= 1;
1138
1139        if (prepare_revision_walk(opts->revs))
1140                return error(_("revision walk setup failed"));
1141
1142        if (!opts->revs->commits)
1143                return error(_("empty commit set passed"));
1144        return 0;
1145}
1146
1147static int read_and_refresh_cache(struct replay_opts *opts)
1148{
1149        static struct lock_file index_lock;
1150        int index_fd = hold_locked_index(&index_lock, 0);
1151        if (read_index_preload(&the_index, NULL) < 0) {
1152                rollback_lock_file(&index_lock);
1153                return error(_("git %s: failed to read the index"),
1154                        _(action_name(opts)));
1155        }
1156        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1157        if (the_index.cache_changed && index_fd >= 0) {
1158                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1159                        rollback_lock_file(&index_lock);
1160                        return error(_("git %s: failed to refresh the index"),
1161                                _(action_name(opts)));
1162                }
1163        }
1164        rollback_lock_file(&index_lock);
1165        return 0;
1166}
1167
1168struct todo_item {
1169        enum todo_command command;
1170        struct commit *commit;
1171        const char *arg;
1172        int arg_len;
1173        size_t offset_in_buf;
1174};
1175
1176struct todo_list {
1177        struct strbuf buf;
1178        struct todo_item *items;
1179        int nr, alloc, current;
1180};
1181
1182#define TODO_LIST_INIT { STRBUF_INIT }
1183
1184static void todo_list_release(struct todo_list *todo_list)
1185{
1186        strbuf_release(&todo_list->buf);
1187        free(todo_list->items);
1188        todo_list->items = NULL;
1189        todo_list->nr = todo_list->alloc = 0;
1190}
1191
1192static struct todo_item *append_new_todo(struct todo_list *todo_list)
1193{
1194        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1195        return todo_list->items + todo_list->nr++;
1196}
1197
1198static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1199{
1200        unsigned char commit_sha1[20];
1201        char *end_of_object_name;
1202        int i, saved, status, padding;
1203
1204        /* left-trim */
1205        bol += strspn(bol, " \t");
1206
1207        if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1208                item->command = TODO_COMMENT;
1209                item->commit = NULL;
1210                item->arg = bol;
1211                item->arg_len = eol - bol;
1212                return 0;
1213        }
1214
1215        for (i = 0; i < TODO_COMMENT; i++)
1216                if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1217                        item->command = i;
1218                        break;
1219                } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1220                        bol++;
1221                        item->command = i;
1222                        break;
1223                }
1224        if (i >= TODO_COMMENT)
1225                return -1;
1226
1227        if (item->command == TODO_NOOP) {
1228                item->commit = NULL;
1229                item->arg = bol;
1230                item->arg_len = eol - bol;
1231                return 0;
1232        }
1233
1234        /* Eat up extra spaces/ tabs before object name */
1235        padding = strspn(bol, " \t");
1236        if (!padding)
1237                return -1;
1238        bol += padding;
1239
1240        if (item->command == TODO_EXEC) {
1241                item->arg = bol;
1242                item->arg_len = (int)(eol - bol);
1243                return 0;
1244        }
1245
1246        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1247        saved = *end_of_object_name;
1248        *end_of_object_name = '\0';
1249        status = get_sha1(bol, commit_sha1);
1250        *end_of_object_name = saved;
1251
1252        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1253        item->arg_len = (int)(eol - item->arg);
1254
1255        if (status < 0)
1256                return -1;
1257
1258        item->commit = lookup_commit_reference(commit_sha1);
1259        return !item->commit;
1260}
1261
1262static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1263{
1264        struct todo_item *item;
1265        char *p = buf, *next_p;
1266        int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1267
1268        for (i = 1; *p; i++, p = next_p) {
1269                char *eol = strchrnul(p, '\n');
1270
1271                next_p = *eol ? eol + 1 /* skip LF */ : eol;
1272
1273                if (p != eol && eol[-1] == '\r')
1274                        eol--; /* strip Carriage Return */
1275
1276                item = append_new_todo(todo_list);
1277                item->offset_in_buf = p - todo_list->buf.buf;
1278                if (parse_insn_line(item, p, eol)) {
1279                        res = error(_("invalid line %d: %.*s"),
1280                                i, (int)(eol - p), p);
1281                        item->command = TODO_NOOP;
1282                }
1283
1284                if (fixup_okay)
1285                        ; /* do nothing */
1286                else if (is_fixup(item->command))
1287                        return error(_("cannot '%s' without a previous commit"),
1288                                command_to_string(item->command));
1289                else if (!is_noop(item->command))
1290                        fixup_okay = 1;
1291        }
1292
1293        return res;
1294}
1295
1296static int read_populate_todo(struct todo_list *todo_list,
1297                        struct replay_opts *opts)
1298{
1299        const char *todo_file = get_todo_path(opts);
1300        int fd, res;
1301
1302        strbuf_reset(&todo_list->buf);
1303        fd = open(todo_file, O_RDONLY);
1304        if (fd < 0)
1305                return error_errno(_("could not open '%s'"), todo_file);
1306        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1307                close(fd);
1308                return error(_("could not read '%s'."), todo_file);
1309        }
1310        close(fd);
1311
1312        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1313        if (res)
1314                return error(_("unusable instruction sheet: '%s'"), todo_file);
1315
1316        if (!todo_list->nr &&
1317            (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1318                return error(_("no commits parsed."));
1319
1320        if (!is_rebase_i(opts)) {
1321                enum todo_command valid =
1322                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1323                int i;
1324
1325                for (i = 0; i < todo_list->nr; i++)
1326                        if (valid == todo_list->items[i].command)
1327                                continue;
1328                        else if (valid == TODO_PICK)
1329                                return error(_("cannot cherry-pick during a revert."));
1330                        else
1331                                return error(_("cannot revert during a cherry-pick."));
1332        }
1333
1334        return 0;
1335}
1336
1337static int git_config_string_dup(char **dest,
1338                                 const char *var, const char *value)
1339{
1340        if (!value)
1341                return config_error_nonbool(var);
1342        free(*dest);
1343        *dest = xstrdup(value);
1344        return 0;
1345}
1346
1347static int populate_opts_cb(const char *key, const char *value, void *data)
1348{
1349        struct replay_opts *opts = data;
1350        int error_flag = 1;
1351
1352        if (!value)
1353                error_flag = 0;
1354        else if (!strcmp(key, "options.no-commit"))
1355                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1356        else if (!strcmp(key, "options.edit"))
1357                opts->edit = git_config_bool_or_int(key, value, &error_flag);
1358        else if (!strcmp(key, "options.signoff"))
1359                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1360        else if (!strcmp(key, "options.record-origin"))
1361                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1362        else if (!strcmp(key, "options.allow-ff"))
1363                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1364        else if (!strcmp(key, "options.mainline"))
1365                opts->mainline = git_config_int(key, value);
1366        else if (!strcmp(key, "options.strategy"))
1367                git_config_string_dup(&opts->strategy, key, value);
1368        else if (!strcmp(key, "options.gpg-sign"))
1369                git_config_string_dup(&opts->gpg_sign, key, value);
1370        else if (!strcmp(key, "options.strategy-option")) {
1371                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1372                opts->xopts[opts->xopts_nr++] = xstrdup(value);
1373        } else
1374                return error(_("invalid key: %s"), key);
1375
1376        if (!error_flag)
1377                return error(_("invalid value for %s: %s"), key, value);
1378
1379        return 0;
1380}
1381
1382static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1383{
1384        int i;
1385
1386        strbuf_reset(buf);
1387        if (!read_oneliner(buf, rebase_path_strategy(), 0))
1388                return;
1389        opts->strategy = strbuf_detach(buf, NULL);
1390        if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1391                return;
1392
1393        opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1394        for (i = 0; i < opts->xopts_nr; i++) {
1395                const char *arg = opts->xopts[i];
1396
1397                skip_prefix(arg, "--", &arg);
1398                opts->xopts[i] = xstrdup(arg);
1399        }
1400}
1401
1402static int read_populate_opts(struct replay_opts *opts)
1403{
1404        if (is_rebase_i(opts)) {
1405                struct strbuf buf = STRBUF_INIT;
1406
1407                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1408                        if (!starts_with(buf.buf, "-S"))
1409                                strbuf_reset(&buf);
1410                        else {
1411                                free(opts->gpg_sign);
1412                                opts->gpg_sign = xstrdup(buf.buf + 2);
1413                        }
1414                }
1415
1416                if (file_exists(rebase_path_verbose()))
1417                        opts->verbose = 1;
1418
1419                read_strategy_opts(opts, &buf);
1420                strbuf_release(&buf);
1421
1422                return 0;
1423        }
1424
1425        if (!file_exists(git_path_opts_file()))
1426                return 0;
1427        /*
1428         * The function git_parse_source(), called from git_config_from_file(),
1429         * may die() in case of a syntactically incorrect file. We do not care
1430         * about this case, though, because we wrote that file ourselves, so we
1431         * are pretty certain that it is syntactically correct.
1432         */
1433        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1434                return error(_("malformed options sheet: '%s'"),
1435                        git_path_opts_file());
1436        return 0;
1437}
1438
1439static int walk_revs_populate_todo(struct todo_list *todo_list,
1440                                struct replay_opts *opts)
1441{
1442        enum todo_command command = opts->action == REPLAY_PICK ?
1443                TODO_PICK : TODO_REVERT;
1444        const char *command_string = todo_command_info[command].str;
1445        struct commit *commit;
1446
1447        if (prepare_revs(opts))
1448                return -1;
1449
1450        while ((commit = get_revision(opts->revs))) {
1451                struct todo_item *item = append_new_todo(todo_list);
1452                const char *commit_buffer = get_commit_buffer(commit, NULL);
1453                const char *subject;
1454                int subject_len;
1455
1456                item->command = command;
1457                item->commit = commit;
1458                item->arg = NULL;
1459                item->arg_len = 0;
1460                item->offset_in_buf = todo_list->buf.len;
1461                subject_len = find_commit_subject(commit_buffer, &subject);
1462                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1463                        short_commit_name(commit), subject_len, subject);
1464                unuse_commit_buffer(commit, commit_buffer);
1465        }
1466        return 0;
1467}
1468
1469static int create_seq_dir(void)
1470{
1471        if (file_exists(git_path_seq_dir())) {
1472                error(_("a cherry-pick or revert is already in progress"));
1473                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1474                return -1;
1475        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1476                return error_errno(_("could not create sequencer directory '%s'"),
1477                                   git_path_seq_dir());
1478        return 0;
1479}
1480
1481static int save_head(const char *head)
1482{
1483        static struct lock_file head_lock;
1484        struct strbuf buf = STRBUF_INIT;
1485        int fd;
1486
1487        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1488        if (fd < 0) {
1489                rollback_lock_file(&head_lock);
1490                return error_errno(_("could not lock HEAD"));
1491        }
1492        strbuf_addf(&buf, "%s\n", head);
1493        if (write_in_full(fd, buf.buf, buf.len) < 0) {
1494                rollback_lock_file(&head_lock);
1495                return error_errno(_("could not write to '%s'"),
1496                                   git_path_head_file());
1497        }
1498        if (commit_lock_file(&head_lock) < 0) {
1499                rollback_lock_file(&head_lock);
1500                return error(_("failed to finalize '%s'."), git_path_head_file());
1501        }
1502        return 0;
1503}
1504
1505static int rollback_is_safe(void)
1506{
1507        struct strbuf sb = STRBUF_INIT;
1508        struct object_id expected_head, actual_head;
1509
1510        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1511                strbuf_trim(&sb);
1512                if (get_oid_hex(sb.buf, &expected_head)) {
1513                        strbuf_release(&sb);
1514                        die(_("could not parse %s"), git_path_abort_safety_file());
1515                }
1516                strbuf_release(&sb);
1517        }
1518        else if (errno == ENOENT)
1519                oidclr(&expected_head);
1520        else
1521                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1522
1523        if (get_oid("HEAD", &actual_head))
1524                oidclr(&actual_head);
1525
1526        return !oidcmp(&actual_head, &expected_head);
1527}
1528
1529static int reset_for_rollback(const unsigned char *sha1)
1530{
1531        const char *argv[4];    /* reset --merge <arg> + NULL */
1532
1533        argv[0] = "reset";
1534        argv[1] = "--merge";
1535        argv[2] = sha1_to_hex(sha1);
1536        argv[3] = NULL;
1537        return run_command_v_opt(argv, RUN_GIT_CMD);
1538}
1539
1540static int rollback_single_pick(void)
1541{
1542        unsigned char head_sha1[20];
1543
1544        if (!file_exists(git_path_cherry_pick_head()) &&
1545            !file_exists(git_path_revert_head()))
1546                return error(_("no cherry-pick or revert in progress"));
1547        if (read_ref_full("HEAD", 0, head_sha1, NULL))
1548                return error(_("cannot resolve HEAD"));
1549        if (is_null_sha1(head_sha1))
1550                return error(_("cannot abort from a branch yet to be born"));
1551        return reset_for_rollback(head_sha1);
1552}
1553
1554int sequencer_rollback(struct replay_opts *opts)
1555{
1556        FILE *f;
1557        unsigned char sha1[20];
1558        struct strbuf buf = STRBUF_INIT;
1559
1560        f = fopen(git_path_head_file(), "r");
1561        if (!f && errno == ENOENT) {
1562                /*
1563                 * There is no multiple-cherry-pick in progress.
1564                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1565                 * a single-cherry-pick in progress, abort that.
1566                 */
1567                return rollback_single_pick();
1568        }
1569        if (!f)
1570                return error_errno(_("cannot open '%s'"), git_path_head_file());
1571        if (strbuf_getline_lf(&buf, f)) {
1572                error(_("cannot read '%s': %s"), git_path_head_file(),
1573                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1574                fclose(f);
1575                goto fail;
1576        }
1577        fclose(f);
1578        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1579                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1580                        git_path_head_file());
1581                goto fail;
1582        }
1583        if (is_null_sha1(sha1)) {
1584                error(_("cannot abort from a branch yet to be born"));
1585                goto fail;
1586        }
1587
1588        if (!rollback_is_safe()) {
1589                /* Do not error, just do not rollback */
1590                warning(_("You seem to have moved HEAD. "
1591                          "Not rewinding, check your HEAD!"));
1592        } else
1593        if (reset_for_rollback(sha1))
1594                goto fail;
1595        strbuf_release(&buf);
1596        return sequencer_remove_state(opts);
1597fail:
1598        strbuf_release(&buf);
1599        return -1;
1600}
1601
1602static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1603{
1604        static struct lock_file todo_lock;
1605        const char *todo_path = get_todo_path(opts);
1606        int next = todo_list->current, offset, fd;
1607
1608        /*
1609         * rebase -i writes "git-rebase-todo" without the currently executing
1610         * command, appending it to "done" instead.
1611         */
1612        if (is_rebase_i(opts))
1613                next++;
1614
1615        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1616        if (fd < 0)
1617                return error_errno(_("could not lock '%s'"), todo_path);
1618        offset = next < todo_list->nr ?
1619                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1620        if (write_in_full(fd, todo_list->buf.buf + offset,
1621                        todo_list->buf.len - offset) < 0)
1622                return error_errno(_("could not write to '%s'"), todo_path);
1623        if (commit_lock_file(&todo_lock) < 0)
1624                return error(_("failed to finalize '%s'."), todo_path);
1625
1626        if (is_rebase_i(opts)) {
1627                const char *done_path = rebase_path_done();
1628                int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1629                int prev_offset = !next ? 0 :
1630                        todo_list->items[next - 1].offset_in_buf;
1631
1632                if (fd >= 0 && offset > prev_offset &&
1633                    write_in_full(fd, todo_list->buf.buf + prev_offset,
1634                                  offset - prev_offset) < 0) {
1635                        close(fd);
1636                        return error_errno(_("could not write to '%s'"),
1637                                           done_path);
1638                }
1639                if (fd >= 0)
1640                        close(fd);
1641        }
1642        return 0;
1643}
1644
1645static int save_opts(struct replay_opts *opts)
1646{
1647        const char *opts_file = git_path_opts_file();
1648        int res = 0;
1649
1650        if (opts->no_commit)
1651                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1652        if (opts->edit)
1653                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1654        if (opts->signoff)
1655                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1656        if (opts->record_origin)
1657                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1658        if (opts->allow_ff)
1659                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1660        if (opts->mainline) {
1661                struct strbuf buf = STRBUF_INIT;
1662                strbuf_addf(&buf, "%d", opts->mainline);
1663                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1664                strbuf_release(&buf);
1665        }
1666        if (opts->strategy)
1667                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1668        if (opts->gpg_sign)
1669                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1670        if (opts->xopts) {
1671                int i;
1672                for (i = 0; i < opts->xopts_nr; i++)
1673                        res |= git_config_set_multivar_in_file_gently(opts_file,
1674                                                        "options.strategy-option",
1675                                                        opts->xopts[i], "^$", 0);
1676        }
1677        return res;
1678}
1679
1680static int make_patch(struct commit *commit, struct replay_opts *opts)
1681{
1682        struct strbuf buf = STRBUF_INIT;
1683        struct rev_info log_tree_opt;
1684        const char *subject, *p;
1685        int res = 0;
1686
1687        p = short_commit_name(commit);
1688        if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1689                return -1;
1690
1691        strbuf_addf(&buf, "%s/patch", get_dir(opts));
1692        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1693        init_revisions(&log_tree_opt, NULL);
1694        log_tree_opt.abbrev = 0;
1695        log_tree_opt.diff = 1;
1696        log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1697        log_tree_opt.disable_stdin = 1;
1698        log_tree_opt.no_commit_id = 1;
1699        log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1700        log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1701        if (!log_tree_opt.diffopt.file)
1702                res |= error_errno(_("could not open '%s'"), buf.buf);
1703        else {
1704                res |= log_tree_commit(&log_tree_opt, commit);
1705                fclose(log_tree_opt.diffopt.file);
1706        }
1707        strbuf_reset(&buf);
1708
1709        strbuf_addf(&buf, "%s/message", get_dir(opts));
1710        if (!file_exists(buf.buf)) {
1711                const char *commit_buffer = get_commit_buffer(commit, NULL);
1712                find_commit_subject(commit_buffer, &subject);
1713                res |= write_message(subject, strlen(subject), buf.buf, 1);
1714                unuse_commit_buffer(commit, commit_buffer);
1715        }
1716        strbuf_release(&buf);
1717
1718        return res;
1719}
1720
1721static int intend_to_amend(void)
1722{
1723        unsigned char head[20];
1724        char *p;
1725
1726        if (get_sha1("HEAD", head))
1727                return error(_("cannot read HEAD"));
1728
1729        p = sha1_to_hex(head);
1730        return write_message(p, strlen(p), rebase_path_amend(), 1);
1731}
1732
1733static int error_with_patch(struct commit *commit,
1734        const char *subject, int subject_len,
1735        struct replay_opts *opts, int exit_code, int to_amend)
1736{
1737        if (make_patch(commit, opts))
1738                return -1;
1739
1740        if (to_amend) {
1741                if (intend_to_amend())
1742                        return -1;
1743
1744                fprintf(stderr, "You can amend the commit now, with\n"
1745                        "\n"
1746                        "  git commit --amend %s\n"
1747                        "\n"
1748                        "Once you are satisfied with your changes, run\n"
1749                        "\n"
1750                        "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
1751        } else if (exit_code)
1752                fprintf(stderr, "Could not apply %s... %.*s\n",
1753                        short_commit_name(commit), subject_len, subject);
1754
1755        return exit_code;
1756}
1757
1758static int error_failed_squash(struct commit *commit,
1759        struct replay_opts *opts, int subject_len, const char *subject)
1760{
1761        if (rename(rebase_path_squash_msg(), rebase_path_message()))
1762                return error(_("could not rename '%s' to '%s'"),
1763                        rebase_path_squash_msg(), rebase_path_message());
1764        unlink(rebase_path_fixup_msg());
1765        unlink(git_path("MERGE_MSG"));
1766        if (copy_file(git_path("MERGE_MSG"), rebase_path_message(), 0666))
1767                return error(_("could not copy '%s' to '%s'"),
1768                             rebase_path_message(), git_path("MERGE_MSG"));
1769        return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1770}
1771
1772static int do_exec(const char *command_line)
1773{
1774        const char *child_argv[] = { NULL, NULL };
1775        int dirty, status;
1776
1777        fprintf(stderr, "Executing: %s\n", command_line);
1778        child_argv[0] = command_line;
1779        status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1780
1781        /* force re-reading of the cache */
1782        if (discard_cache() < 0 || read_cache() < 0)
1783                return error(_("could not read index"));
1784
1785        dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1786
1787        if (status) {
1788                warning(_("execution failed: %s\n%s"
1789                          "You can fix the problem, and then run\n"
1790                          "\n"
1791                          "  git rebase --continue\n"
1792                          "\n"),
1793                        command_line,
1794                        dirty ? N_("and made changes to the index and/or the "
1795                                "working tree\n") : "");
1796                if (status == 127)
1797                        /* command not found */
1798                        status = 1;
1799        } else if (dirty) {
1800                warning(_("execution succeeded: %s\nbut "
1801                          "left changes to the index and/or the working tree\n"
1802                          "Commit or stash your changes, and then run\n"
1803                          "\n"
1804                          "  git rebase --continue\n"
1805                          "\n"), command_line);
1806                status = 1;
1807        }
1808
1809        return status;
1810}
1811
1812static int is_final_fixup(struct todo_list *todo_list)
1813{
1814        int i = todo_list->current;
1815
1816        if (!is_fixup(todo_list->items[i].command))
1817                return 0;
1818
1819        while (++i < todo_list->nr)
1820                if (is_fixup(todo_list->items[i].command))
1821                        return 0;
1822                else if (!is_noop(todo_list->items[i].command))
1823                        break;
1824        return 1;
1825}
1826
1827static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1828{
1829        int i;
1830
1831        for (i = todo_list->current + offset; i < todo_list->nr; i++)
1832                if (!is_noop(todo_list->items[i].command))
1833                        return todo_list->items[i].command;
1834
1835        return -1;
1836}
1837
1838static int apply_autostash(struct replay_opts *opts)
1839{
1840        struct strbuf stash_sha1 = STRBUF_INIT;
1841        struct child_process child = CHILD_PROCESS_INIT;
1842        int ret = 0;
1843
1844        if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1845                strbuf_release(&stash_sha1);
1846                return 0;
1847        }
1848        strbuf_trim(&stash_sha1);
1849
1850        child.git_cmd = 1;
1851        argv_array_push(&child.args, "stash");
1852        argv_array_push(&child.args, "apply");
1853        argv_array_push(&child.args, stash_sha1.buf);
1854        if (!run_command(&child))
1855                printf(_("Applied autostash."));
1856        else {
1857                struct child_process store = CHILD_PROCESS_INIT;
1858
1859                store.git_cmd = 1;
1860                argv_array_push(&store.args, "stash");
1861                argv_array_push(&store.args, "store");
1862                argv_array_push(&store.args, "-m");
1863                argv_array_push(&store.args, "autostash");
1864                argv_array_push(&store.args, "-q");
1865                argv_array_push(&store.args, stash_sha1.buf);
1866                if (run_command(&store))
1867                        ret = error(_("cannot store %s"), stash_sha1.buf);
1868                else
1869                        printf(_("Applying autostash resulted in conflicts.\n"
1870                                "Your changes are safe in the stash.\n"
1871                                "You can run \"git stash pop\" or"
1872                                " \"git stash drop\" at any time.\n"));
1873        }
1874
1875        strbuf_release(&stash_sha1);
1876        return ret;
1877}
1878
1879static const char *reflog_message(struct replay_opts *opts,
1880        const char *sub_action, const char *fmt, ...)
1881{
1882        va_list ap;
1883        static struct strbuf buf = STRBUF_INIT;
1884
1885        va_start(ap, fmt);
1886        strbuf_reset(&buf);
1887        strbuf_addstr(&buf, action_name(opts));
1888        if (sub_action)
1889                strbuf_addf(&buf, " (%s)", sub_action);
1890        if (fmt) {
1891                strbuf_addstr(&buf, ": ");
1892                strbuf_vaddf(&buf, fmt, ap);
1893        }
1894        va_end(ap);
1895
1896        return buf.buf;
1897}
1898
1899static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1900{
1901        int res = 0;
1902
1903        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1904        if (opts->allow_ff)
1905                assert(!(opts->signoff || opts->no_commit ||
1906                                opts->record_origin || opts->edit));
1907        if (read_and_refresh_cache(opts))
1908                return -1;
1909
1910        while (todo_list->current < todo_list->nr) {
1911                struct todo_item *item = todo_list->items + todo_list->current;
1912                if (save_todo(todo_list, opts))
1913                        return -1;
1914                if (is_rebase_i(opts)) {
1915                        unlink(rebase_path_message());
1916                        unlink(rebase_path_author_script());
1917                        unlink(rebase_path_stopped_sha());
1918                        unlink(rebase_path_amend());
1919                }
1920                if (item->command <= TODO_SQUASH) {
1921                        if (is_rebase_i(opts))
1922                                setenv("GIT_REFLOG_ACTION", reflog_message(opts,
1923                                        command_to_string(item->command), NULL),
1924                                        1);
1925                        res = do_pick_commit(item->command, item->commit,
1926                                        opts, is_final_fixup(todo_list));
1927                        if (is_rebase_i(opts) && res < 0) {
1928                                /* Reschedule */
1929                                todo_list->current--;
1930                                if (save_todo(todo_list, opts))
1931                                        return -1;
1932                        }
1933                        if (item->command == TODO_EDIT) {
1934                                struct commit *commit = item->commit;
1935                                if (!res)
1936                                        warning(_("stopped at %s... %.*s"),
1937                                                short_commit_name(commit),
1938                                                item->arg_len, item->arg);
1939                                return error_with_patch(commit,
1940                                        item->arg, item->arg_len, opts, res,
1941                                        !res);
1942                        }
1943                        if (is_rebase_i(opts) && !res)
1944                                record_in_rewritten(&item->commit->object.oid,
1945                                        peek_command(todo_list, 1));
1946                        if (res && is_fixup(item->command)) {
1947                                if (res == 1)
1948                                        intend_to_amend();
1949                                return error_failed_squash(item->commit, opts,
1950                                        item->arg_len, item->arg);
1951                        } else if (res && is_rebase_i(opts))
1952                                return res | error_with_patch(item->commit,
1953                                        item->arg, item->arg_len, opts, res,
1954                                        item->command == TODO_REWORD);
1955                } else if (item->command == TODO_EXEC) {
1956                        char *end_of_arg = (char *)(item->arg + item->arg_len);
1957                        int saved = *end_of_arg;
1958
1959                        *end_of_arg = '\0';
1960                        res = do_exec(item->arg);
1961                        *end_of_arg = saved;
1962                } else if (!is_noop(item->command))
1963                        return error(_("unknown command %d"), item->command);
1964
1965                todo_list->current++;
1966                if (res)
1967                        return res;
1968        }
1969
1970        if (is_rebase_i(opts)) {
1971                struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
1972                struct stat st;
1973
1974                /* Stopped in the middle, as planned? */
1975                if (todo_list->current < todo_list->nr)
1976                        return 0;
1977
1978                if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
1979                                starts_with(head_ref.buf, "refs/")) {
1980                        const char *msg;
1981                        unsigned char head[20], orig[20];
1982                        int res;
1983
1984                        if (get_sha1("HEAD", head)) {
1985                                res = error(_("cannot read HEAD"));
1986cleanup_head_ref:
1987                                strbuf_release(&head_ref);
1988                                strbuf_release(&buf);
1989                                return res;
1990                        }
1991                        if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
1992                                        get_sha1_hex(buf.buf, orig)) {
1993                                res = error(_("could not read orig-head"));
1994                                goto cleanup_head_ref;
1995                        }
1996                        if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
1997                                res = error(_("could not read 'onto'"));
1998                                goto cleanup_head_ref;
1999                        }
2000                        msg = reflog_message(opts, "finish", "%s onto %s",
2001                                head_ref.buf, buf.buf);
2002                        if (update_ref(msg, head_ref.buf, head, orig,
2003                                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2004                                res = error(_("could not update %s"),
2005                                        head_ref.buf);
2006                                goto cleanup_head_ref;
2007                        }
2008                        msg = reflog_message(opts, "finish", "returning to %s",
2009                                head_ref.buf);
2010                        if (create_symref("HEAD", head_ref.buf, msg)) {
2011                                res = error(_("could not update HEAD to %s"),
2012                                        head_ref.buf);
2013                                goto cleanup_head_ref;
2014                        }
2015                        strbuf_reset(&buf);
2016                }
2017
2018                if (opts->verbose) {
2019                        struct rev_info log_tree_opt;
2020                        struct object_id orig, head;
2021
2022                        memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2023                        init_revisions(&log_tree_opt, NULL);
2024                        log_tree_opt.diff = 1;
2025                        log_tree_opt.diffopt.output_format =
2026                                DIFF_FORMAT_DIFFSTAT;
2027                        log_tree_opt.disable_stdin = 1;
2028
2029                        if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2030                            !get_sha1(buf.buf, orig.hash) &&
2031                            !get_sha1("HEAD", head.hash)) {
2032                                diff_tree_sha1(orig.hash, head.hash,
2033                                               "", &log_tree_opt.diffopt);
2034                                log_tree_diff_flush(&log_tree_opt);
2035                        }
2036                }
2037                flush_rewritten_pending();
2038                if (!stat(rebase_path_rewritten_list(), &st) &&
2039                                st.st_size > 0) {
2040                        struct child_process child = CHILD_PROCESS_INIT;
2041                        const char *post_rewrite_hook =
2042                                find_hook("post-rewrite");
2043
2044                        child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2045                        child.git_cmd = 1;
2046                        argv_array_push(&child.args, "notes");
2047                        argv_array_push(&child.args, "copy");
2048                        argv_array_push(&child.args, "--for-rewrite=rebase");
2049                        /* we don't care if this copying failed */
2050                        run_command(&child);
2051
2052                        if (post_rewrite_hook) {
2053                                struct child_process hook = CHILD_PROCESS_INIT;
2054
2055                                hook.in = open(rebase_path_rewritten_list(),
2056                                        O_RDONLY);
2057                                hook.stdout_to_stderr = 1;
2058                                argv_array_push(&hook.args, post_rewrite_hook);
2059                                argv_array_push(&hook.args, "rebase");
2060                                /* we don't care if this hook failed */
2061                                run_command(&hook);
2062                        }
2063                }
2064                apply_autostash(opts);
2065
2066                strbuf_release(&buf);
2067                strbuf_release(&head_ref);
2068        }
2069
2070        /*
2071         * Sequence of picks finished successfully; cleanup by
2072         * removing the .git/sequencer directory
2073         */
2074        return sequencer_remove_state(opts);
2075}
2076
2077static int continue_single_pick(void)
2078{
2079        const char *argv[] = { "commit", NULL };
2080
2081        if (!file_exists(git_path_cherry_pick_head()) &&
2082            !file_exists(git_path_revert_head()))
2083                return error(_("no cherry-pick or revert in progress"));
2084        return run_command_v_opt(argv, RUN_GIT_CMD);
2085}
2086
2087static int commit_staged_changes(struct replay_opts *opts)
2088{
2089        int amend = 0;
2090
2091        if (has_unstaged_changes(1))
2092                return error(_("cannot rebase: You have unstaged changes."));
2093        if (!has_uncommitted_changes(0)) {
2094                const char *cherry_pick_head = git_path("CHERRY_PICK_HEAD");
2095
2096                if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2097                        return error(_("could not remove CHERRY_PICK_HEAD"));
2098                return 0;
2099        }
2100
2101        if (file_exists(rebase_path_amend())) {
2102                struct strbuf rev = STRBUF_INIT;
2103                unsigned char head[20], to_amend[20];
2104
2105                if (get_sha1("HEAD", head))
2106                        return error(_("cannot amend non-existing commit"));
2107                if (!read_oneliner(&rev, rebase_path_amend(), 0))
2108                        return error(_("invalid file: '%s'"), rebase_path_amend());
2109                if (get_sha1_hex(rev.buf, to_amend))
2110                        return error(_("invalid contents: '%s'"),
2111                                rebase_path_amend());
2112                if (hashcmp(head, to_amend))
2113                        return error(_("\nYou have uncommitted changes in your "
2114                                       "working tree. Please, commit them\n"
2115                                       "first and then run 'git rebase "
2116                                       "--continue' again."));
2117
2118                strbuf_release(&rev);
2119                amend = 1;
2120        }
2121
2122        if (run_git_commit(rebase_path_message(), opts, 1, 1, amend, 0))
2123                return error(_("could not commit staged changes."));
2124        unlink(rebase_path_amend());
2125        return 0;
2126}
2127
2128int sequencer_continue(struct replay_opts *opts)
2129{
2130        struct todo_list todo_list = TODO_LIST_INIT;
2131        int res;
2132
2133        if (read_and_refresh_cache(opts))
2134                return -1;
2135
2136        if (is_rebase_i(opts)) {
2137                if (commit_staged_changes(opts))
2138                        return -1;
2139        } else if (!file_exists(get_todo_path(opts)))
2140                return continue_single_pick();
2141        if (read_populate_opts(opts))
2142                return -1;
2143        if ((res = read_populate_todo(&todo_list, opts)))
2144                goto release_todo_list;
2145
2146        if (!is_rebase_i(opts)) {
2147                /* Verify that the conflict has been resolved */
2148                if (file_exists(git_path_cherry_pick_head()) ||
2149                    file_exists(git_path_revert_head())) {
2150                        res = continue_single_pick();
2151                        if (res)
2152                                goto release_todo_list;
2153                }
2154                if (index_differs_from("HEAD", 0, 0)) {
2155                        res = error_dirty_index(opts);
2156                        goto release_todo_list;
2157                }
2158                todo_list.current++;
2159        } else if (file_exists(rebase_path_stopped_sha())) {
2160                struct strbuf buf = STRBUF_INIT;
2161                struct object_id oid;
2162
2163                if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2164                    !get_sha1_committish(buf.buf, oid.hash))
2165                        record_in_rewritten(&oid, peek_command(&todo_list, 0));
2166                strbuf_release(&buf);
2167        }
2168
2169        res = pick_commits(&todo_list, opts);
2170release_todo_list:
2171        todo_list_release(&todo_list);
2172        return res;
2173}
2174
2175static int single_pick(struct commit *cmit, struct replay_opts *opts)
2176{
2177        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2178        return do_pick_commit(opts->action == REPLAY_PICK ?
2179                TODO_PICK : TODO_REVERT, cmit, opts, 0);
2180}
2181
2182int sequencer_pick_revisions(struct replay_opts *opts)
2183{
2184        struct todo_list todo_list = TODO_LIST_INIT;
2185        unsigned char sha1[20];
2186        int i, res;
2187
2188        assert(opts->revs);
2189        if (read_and_refresh_cache(opts))
2190                return -1;
2191
2192        for (i = 0; i < opts->revs->pending.nr; i++) {
2193                unsigned char sha1[20];
2194                const char *name = opts->revs->pending.objects[i].name;
2195
2196                /* This happens when using --stdin. */
2197                if (!strlen(name))
2198                        continue;
2199
2200                if (!get_sha1(name, sha1)) {
2201                        if (!lookup_commit_reference_gently(sha1, 1)) {
2202                                enum object_type type = sha1_object_info(sha1, NULL);
2203                                return error(_("%s: can't cherry-pick a %s"),
2204                                        name, typename(type));
2205                        }
2206                } else
2207                        return error(_("%s: bad revision"), name);
2208        }
2209
2210        /*
2211         * If we were called as "git cherry-pick <commit>", just
2212         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2213         * REVERT_HEAD, and don't touch the sequencer state.
2214         * This means it is possible to cherry-pick in the middle
2215         * of a cherry-pick sequence.
2216         */
2217        if (opts->revs->cmdline.nr == 1 &&
2218            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2219            opts->revs->no_walk &&
2220            !opts->revs->cmdline.rev->flags) {
2221                struct commit *cmit;
2222                if (prepare_revision_walk(opts->revs))
2223                        return error(_("revision walk setup failed"));
2224                cmit = get_revision(opts->revs);
2225                if (!cmit || get_revision(opts->revs))
2226                        return error("BUG: expected exactly one commit from walk");
2227                return single_pick(cmit, opts);
2228        }
2229
2230        /*
2231         * Start a new cherry-pick/ revert sequence; but
2232         * first, make sure that an existing one isn't in
2233         * progress
2234         */
2235
2236        if (walk_revs_populate_todo(&todo_list, opts) ||
2237                        create_seq_dir() < 0)
2238                return -1;
2239        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
2240                return error(_("can't revert as initial commit"));
2241        if (save_head(sha1_to_hex(sha1)))
2242                return -1;
2243        if (save_opts(opts))
2244                return -1;
2245        update_abort_safety_file();
2246        res = pick_commits(&todo_list, opts);
2247        todo_list_release(&todo_list);
2248        return res;
2249}
2250
2251void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2252{
2253        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2254        struct strbuf sob = STRBUF_INIT;
2255        int has_footer;
2256
2257        strbuf_addstr(&sob, sign_off_header);
2258        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2259                                getenv("GIT_COMMITTER_EMAIL")));
2260        strbuf_addch(&sob, '\n');
2261
2262        /*
2263         * If the whole message buffer is equal to the sob, pretend that we
2264         * found a conforming footer with a matching sob
2265         */
2266        if (msgbuf->len - ignore_footer == sob.len &&
2267            !strncmp(msgbuf->buf, sob.buf, sob.len))
2268                has_footer = 3;
2269        else
2270                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2271
2272        if (!has_footer) {
2273                const char *append_newlines = NULL;
2274                size_t len = msgbuf->len - ignore_footer;
2275
2276                if (!len) {
2277                        /*
2278                         * The buffer is completely empty.  Leave foom for
2279                         * the title and body to be filled in by the user.
2280                         */
2281                        append_newlines = "\n\n";
2282                } else if (msgbuf->buf[len - 1] != '\n') {
2283                        /*
2284                         * Incomplete line.  Complete the line and add a
2285                         * blank one so that there is an empty line between
2286                         * the message body and the sob.
2287                         */
2288                        append_newlines = "\n\n";
2289                } else if (len == 1) {
2290                        /*
2291                         * Buffer contains a single newline.  Add another
2292                         * so that we leave room for the title and body.
2293                         */
2294                        append_newlines = "\n";
2295                } else if (msgbuf->buf[len - 2] != '\n') {
2296                        /*
2297                         * Buffer ends with a single newline.  Add another
2298                         * so that there is an empty line between the message
2299                         * body and the sob.
2300                         */
2301                        append_newlines = "\n";
2302                } /* else, the buffer already ends with two newlines. */
2303
2304                if (append_newlines)
2305                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2306                                append_newlines, strlen(append_newlines));
2307        }
2308
2309        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2310                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2311                                sob.buf, sob.len);
2312
2313        strbuf_release(&sob);
2314}