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