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