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