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