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