sequencer.con commit sequencer: future-proof remove_sequencer_state() (285abf5)
   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
  19#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  20
  21const char sign_off_header[] = "Signed-off-by: ";
  22static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  23
  24GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  25
  26static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  27static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  28static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  29
  30static const char *get_dir(const struct replay_opts *opts)
  31{
  32        return git_path_seq_dir();
  33}
  34
  35static int is_rfc2822_line(const char *buf, int len)
  36{
  37        int i;
  38
  39        for (i = 0; i < len; i++) {
  40                int ch = buf[i];
  41                if (ch == ':')
  42                        return 1;
  43                if (!isalnum(ch) && ch != '-')
  44                        break;
  45        }
  46
  47        return 0;
  48}
  49
  50static int is_cherry_picked_from_line(const char *buf, int len)
  51{
  52        /*
  53         * We only care that it looks roughly like (cherry picked from ...)
  54         */
  55        return len > strlen(cherry_picked_prefix) + 1 &&
  56                starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
  57}
  58
  59/*
  60 * Returns 0 for non-conforming footer
  61 * Returns 1 for conforming footer
  62 * Returns 2 when sob exists within conforming footer
  63 * Returns 3 when sob exists within conforming footer as last entry
  64 */
  65static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
  66        int ignore_footer)
  67{
  68        char prev;
  69        int i, k;
  70        int len = sb->len - ignore_footer;
  71        const char *buf = sb->buf;
  72        int found_sob = 0;
  73
  74        /* footer must end with newline */
  75        if (!len || buf[len - 1] != '\n')
  76                return 0;
  77
  78        prev = '\0';
  79        for (i = len - 1; i > 0; i--) {
  80                char ch = buf[i];
  81                if (prev == '\n' && ch == '\n') /* paragraph break */
  82                        break;
  83                prev = ch;
  84        }
  85
  86        /* require at least one blank line */
  87        if (prev != '\n' || buf[i] != '\n')
  88                return 0;
  89
  90        /* advance to start of last paragraph */
  91        while (i < len - 1 && buf[i] == '\n')
  92                i++;
  93
  94        for (; i < len; i = k) {
  95                int found_rfc2822;
  96
  97                for (k = i; k < len && buf[k] != '\n'; k++)
  98                        ; /* do nothing */
  99                k++;
 100
 101                found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
 102                if (found_rfc2822 && sob &&
 103                    !strncmp(buf + i, sob->buf, sob->len))
 104                        found_sob = k;
 105
 106                if (!(found_rfc2822 ||
 107                      is_cherry_picked_from_line(buf + i, k - i - 1)))
 108                        return 0;
 109        }
 110        if (found_sob == i)
 111                return 3;
 112        if (found_sob)
 113                return 2;
 114        return 1;
 115}
 116
 117static void remove_sequencer_state(const struct replay_opts *opts)
 118{
 119        struct strbuf dir = STRBUF_INIT;
 120
 121        strbuf_addf(&dir, "%s", get_dir(opts));
 122        remove_dir_recursively(&dir, 0);
 123        strbuf_release(&dir);
 124}
 125
 126static const char *action_name(const struct replay_opts *opts)
 127{
 128        return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
 129}
 130
 131struct commit_message {
 132        char *parent_label;
 133        char *label;
 134        char *subject;
 135        const char *message;
 136};
 137
 138static int get_message(struct commit *commit, struct commit_message *out)
 139{
 140        const char *abbrev, *subject;
 141        int subject_len;
 142
 143        out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 144        abbrev = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
 145
 146        subject_len = find_commit_subject(out->message, &subject);
 147
 148        out->subject = xmemdupz(subject, subject_len);
 149        out->label = xstrfmt("%s... %s", abbrev, out->subject);
 150        out->parent_label = xstrfmt("parent of %s", out->label);
 151
 152        return 0;
 153}
 154
 155static void free_message(struct commit *commit, struct commit_message *msg)
 156{
 157        free(msg->parent_label);
 158        free(msg->label);
 159        free(msg->subject);
 160        unuse_commit_buffer(commit, msg->message);
 161}
 162
 163static void print_advice(int show_hint, struct replay_opts *opts)
 164{
 165        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 166
 167        if (msg) {
 168                fprintf(stderr, "%s\n", msg);
 169                /*
 170                 * A conflict has occurred but the porcelain
 171                 * (typically rebase --interactive) wants to take care
 172                 * of the commit itself so remove CHERRY_PICK_HEAD
 173                 */
 174                unlink(git_path_cherry_pick_head());
 175                return;
 176        }
 177
 178        if (show_hint) {
 179                if (opts->no_commit)
 180                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 181                                 "with 'git add <paths>' or 'git rm <paths>'"));
 182                else
 183                        advise(_("after resolving the conflicts, mark the corrected paths\n"
 184                                 "with 'git add <paths>' or 'git rm <paths>'\n"
 185                                 "and commit the result with 'git commit'"));
 186        }
 187}
 188
 189static int write_message(struct strbuf *msgbuf, const char *filename)
 190{
 191        static struct lock_file msg_file;
 192
 193        int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
 194        if (msg_fd < 0)
 195                return error_errno(_("Could not lock '%s'"), filename);
 196        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 197                return error_errno(_("Could not write to %s"), filename);
 198        strbuf_release(msgbuf);
 199        if (commit_lock_file(&msg_file) < 0)
 200                return error(_("Error wrapping up %s."), filename);
 201
 202        return 0;
 203}
 204
 205static struct tree *empty_tree(void)
 206{
 207        return lookup_tree(EMPTY_TREE_SHA1_BIN);
 208}
 209
 210static int error_dirty_index(struct replay_opts *opts)
 211{
 212        if (read_cache_unmerged())
 213                return error_resolve_conflict(action_name(opts));
 214
 215        /* Different translation strings for cherry-pick and revert */
 216        if (opts->action == REPLAY_PICK)
 217                error(_("Your local changes would be overwritten by cherry-pick."));
 218        else
 219                error(_("Your local changes would be overwritten by revert."));
 220
 221        if (advice_commit_before_merge)
 222                advise(_("Commit your changes or stash them to proceed."));
 223        return -1;
 224}
 225
 226static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 227                        int unborn, struct replay_opts *opts)
 228{
 229        struct ref_transaction *transaction;
 230        struct strbuf sb = STRBUF_INIT;
 231        struct strbuf err = STRBUF_INIT;
 232
 233        read_cache();
 234        if (checkout_fast_forward(from, to, 1))
 235                return -1; /* the callee should have complained already */
 236
 237        strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
 238
 239        transaction = ref_transaction_begin(&err);
 240        if (!transaction ||
 241            ref_transaction_update(transaction, "HEAD",
 242                                   to, unborn ? null_sha1 : from,
 243                                   0, sb.buf, &err) ||
 244            ref_transaction_commit(transaction, &err)) {
 245                ref_transaction_free(transaction);
 246                error("%s", err.buf);
 247                strbuf_release(&sb);
 248                strbuf_release(&err);
 249                return -1;
 250        }
 251
 252        strbuf_release(&sb);
 253        strbuf_release(&err);
 254        ref_transaction_free(transaction);
 255        return 0;
 256}
 257
 258void append_conflicts_hint(struct strbuf *msgbuf)
 259{
 260        int i;
 261
 262        strbuf_addch(msgbuf, '\n');
 263        strbuf_commented_addf(msgbuf, "Conflicts:\n");
 264        for (i = 0; i < active_nr;) {
 265                const struct cache_entry *ce = active_cache[i++];
 266                if (ce_stage(ce)) {
 267                        strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
 268                        while (i < active_nr && !strcmp(ce->name,
 269                                                        active_cache[i]->name))
 270                                i++;
 271                }
 272        }
 273}
 274
 275static int do_recursive_merge(struct commit *base, struct commit *next,
 276                              const char *base_label, const char *next_label,
 277                              unsigned char *head, struct strbuf *msgbuf,
 278                              struct replay_opts *opts)
 279{
 280        struct merge_options o;
 281        struct tree *result, *next_tree, *base_tree, *head_tree;
 282        int clean;
 283        const char **xopt;
 284        static struct lock_file index_lock;
 285
 286        hold_locked_index(&index_lock, 1);
 287
 288        read_cache();
 289
 290        init_merge_options(&o);
 291        o.ancestor = base ? base_label : "(empty tree)";
 292        o.branch1 = "HEAD";
 293        o.branch2 = next ? next_label : "(empty tree)";
 294
 295        head_tree = parse_tree_indirect(head);
 296        next_tree = next ? next->tree : empty_tree();
 297        base_tree = base ? base->tree : empty_tree();
 298
 299        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 300                parse_merge_opt(&o, *xopt);
 301
 302        clean = merge_trees(&o,
 303                            head_tree,
 304                            next_tree, base_tree, &result);
 305        strbuf_release(&o.obuf);
 306        if (clean < 0)
 307                return clean;
 308
 309        if (active_cache_changed &&
 310            write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 311                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 312                return error(_("%s: Unable to write new index file"),
 313                        action_name(opts));
 314        rollback_lock_file(&index_lock);
 315
 316        if (opts->signoff)
 317                append_signoff(msgbuf, 0, 0);
 318
 319        if (!clean)
 320                append_conflicts_hint(msgbuf);
 321
 322        return !clean;
 323}
 324
 325static int is_index_unchanged(void)
 326{
 327        unsigned char head_sha1[20];
 328        struct commit *head_commit;
 329
 330        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
 331                return error(_("Could not resolve HEAD commit\n"));
 332
 333        head_commit = lookup_commit(head_sha1);
 334
 335        /*
 336         * If head_commit is NULL, check_commit, called from
 337         * lookup_commit, would have indicated that head_commit is not
 338         * a commit object already.  parse_commit() will return failure
 339         * without further complaints in such a case.  Otherwise, if
 340         * the commit is invalid, parse_commit() will complain.  So
 341         * there is nothing for us to say here.  Just return failure.
 342         */
 343        if (parse_commit(head_commit))
 344                return -1;
 345
 346        if (!active_cache_tree)
 347                active_cache_tree = cache_tree();
 348
 349        if (!cache_tree_fully_valid(active_cache_tree))
 350                if (cache_tree_update(&the_index, 0))
 351                        return error(_("Unable to update cache tree\n"));
 352
 353        return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
 354}
 355
 356/*
 357 * If we are cherry-pick, and if the merge did not result in
 358 * hand-editing, we will hit this commit and inherit the original
 359 * author date and name.
 360 * If we are revert, or if our cherry-pick results in a hand merge,
 361 * we had better say that the current user is responsible for that.
 362 */
 363static int run_git_commit(const char *defmsg, struct replay_opts *opts,
 364                          int allow_empty)
 365{
 366        struct argv_array array;
 367        int rc;
 368        const char *value;
 369
 370        argv_array_init(&array);
 371        argv_array_push(&array, "commit");
 372        argv_array_push(&array, "-n");
 373
 374        if (opts->gpg_sign)
 375                argv_array_pushf(&array, "-S%s", opts->gpg_sign);
 376        if (opts->signoff)
 377                argv_array_push(&array, "-s");
 378        if (!opts->edit) {
 379                argv_array_push(&array, "-F");
 380                argv_array_push(&array, defmsg);
 381                if (!opts->signoff &&
 382                    !opts->record_origin &&
 383                    git_config_get_value("commit.cleanup", &value))
 384                        argv_array_push(&array, "--cleanup=verbatim");
 385        }
 386
 387        if (allow_empty)
 388                argv_array_push(&array, "--allow-empty");
 389
 390        if (opts->allow_empty_message)
 391                argv_array_push(&array, "--allow-empty-message");
 392
 393        rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
 394        argv_array_clear(&array);
 395        return rc;
 396}
 397
 398static int is_original_commit_empty(struct commit *commit)
 399{
 400        const unsigned char *ptree_sha1;
 401
 402        if (parse_commit(commit))
 403                return error(_("Could not parse commit %s\n"),
 404                             oid_to_hex(&commit->object.oid));
 405        if (commit->parents) {
 406                struct commit *parent = commit->parents->item;
 407                if (parse_commit(parent))
 408                        return error(_("Could not parse parent commit %s\n"),
 409                                oid_to_hex(&parent->object.oid));
 410                ptree_sha1 = parent->tree->object.oid.hash;
 411        } else {
 412                ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
 413        }
 414
 415        return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
 416}
 417
 418/*
 419 * Do we run "git commit" with "--allow-empty"?
 420 */
 421static int allow_empty(struct replay_opts *opts, struct commit *commit)
 422{
 423        int index_unchanged, empty_commit;
 424
 425        /*
 426         * Three cases:
 427         *
 428         * (1) we do not allow empty at all and error out.
 429         *
 430         * (2) we allow ones that were initially empty, but
 431         * forbid the ones that become empty;
 432         *
 433         * (3) we allow both.
 434         */
 435        if (!opts->allow_empty)
 436                return 0; /* let "git commit" barf as necessary */
 437
 438        index_unchanged = is_index_unchanged();
 439        if (index_unchanged < 0)
 440                return index_unchanged;
 441        if (!index_unchanged)
 442                return 0; /* we do not have to say --allow-empty */
 443
 444        if (opts->keep_redundant_commits)
 445                return 1;
 446
 447        empty_commit = is_original_commit_empty(commit);
 448        if (empty_commit < 0)
 449                return empty_commit;
 450        if (!empty_commit)
 451                return 0;
 452        else
 453                return 1;
 454}
 455
 456static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 457{
 458        unsigned char head[20];
 459        struct commit *base, *next, *parent;
 460        const char *base_label, *next_label;
 461        struct commit_message msg = { NULL, NULL, NULL, NULL };
 462        struct strbuf msgbuf = STRBUF_INIT;
 463        int res, unborn = 0, allow;
 464
 465        if (opts->no_commit) {
 466                /*
 467                 * We do not intend to commit immediately.  We just want to
 468                 * merge the differences in, so let's compute the tree
 469                 * that represents the "current" state for merge-recursive
 470                 * to work on.
 471                 */
 472                if (write_cache_as_tree(head, 0, NULL))
 473                        return error(_("Your index file is unmerged."));
 474        } else {
 475                unborn = get_sha1("HEAD", head);
 476                if (unborn)
 477                        hashcpy(head, EMPTY_TREE_SHA1_BIN);
 478                if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
 479                        return error_dirty_index(opts);
 480        }
 481        discard_cache();
 482
 483        if (!commit->parents) {
 484                parent = NULL;
 485        }
 486        else if (commit->parents->next) {
 487                /* Reverting or cherry-picking a merge commit */
 488                int cnt;
 489                struct commit_list *p;
 490
 491                if (!opts->mainline)
 492                        return error(_("Commit %s is a merge but no -m option was given."),
 493                                oid_to_hex(&commit->object.oid));
 494
 495                for (cnt = 1, p = commit->parents;
 496                     cnt != opts->mainline && p;
 497                     cnt++)
 498                        p = p->next;
 499                if (cnt != opts->mainline || !p)
 500                        return error(_("Commit %s does not have parent %d"),
 501                                oid_to_hex(&commit->object.oid), opts->mainline);
 502                parent = p->item;
 503        } else if (0 < opts->mainline)
 504                return error(_("Mainline was specified but commit %s is not a merge."),
 505                        oid_to_hex(&commit->object.oid));
 506        else
 507                parent = commit->parents->item;
 508
 509        if (opts->allow_ff &&
 510            ((parent && !hashcmp(parent->object.oid.hash, head)) ||
 511             (!parent && unborn)))
 512                return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
 513
 514        if (parent && parse_commit(parent) < 0)
 515                /* TRANSLATORS: The first %s will be "revert" or
 516                   "cherry-pick", the second %s a SHA1 */
 517                return error(_("%s: cannot parse parent commit %s"),
 518                        action_name(opts), oid_to_hex(&parent->object.oid));
 519
 520        if (get_message(commit, &msg) != 0)
 521                return error(_("Cannot get commit message for %s"),
 522                        oid_to_hex(&commit->object.oid));
 523
 524        /*
 525         * "commit" is an existing commit.  We would want to apply
 526         * the difference it introduces since its first parent "prev"
 527         * on top of the current HEAD if we are cherry-pick.  Or the
 528         * reverse of it if we are revert.
 529         */
 530
 531        if (opts->action == REPLAY_REVERT) {
 532                base = commit;
 533                base_label = msg.label;
 534                next = parent;
 535                next_label = msg.parent_label;
 536                strbuf_addstr(&msgbuf, "Revert \"");
 537                strbuf_addstr(&msgbuf, msg.subject);
 538                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 539                strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 540
 541                if (commit->parents && commit->parents->next) {
 542                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 543                        strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
 544                }
 545                strbuf_addstr(&msgbuf, ".\n");
 546        } else {
 547                const char *p;
 548
 549                base = parent;
 550                base_label = msg.parent_label;
 551                next = commit;
 552                next_label = msg.label;
 553
 554                /*
 555                 * Append the commit log message to msgbuf; it starts
 556                 * after the tree, parent, author, committer
 557                 * information followed by "\n\n".
 558                 */
 559                p = strstr(msg.message, "\n\n");
 560                if (p)
 561                        strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
 562
 563                if (opts->record_origin) {
 564                        if (!has_conforming_footer(&msgbuf, NULL, 0))
 565                                strbuf_addch(&msgbuf, '\n');
 566                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
 567                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 568                        strbuf_addstr(&msgbuf, ")\n");
 569                }
 570        }
 571
 572        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
 573                res = do_recursive_merge(base, next, base_label, next_label,
 574                                         head, &msgbuf, opts);
 575                if (res < 0)
 576                        return res;
 577                res |= write_message(&msgbuf, git_path_merge_msg());
 578        } else {
 579                struct commit_list *common = NULL;
 580                struct commit_list *remotes = NULL;
 581
 582                res = write_message(&msgbuf, git_path_merge_msg());
 583
 584                commit_list_insert(base, &common);
 585                commit_list_insert(next, &remotes);
 586                res |= try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 587                                        common, sha1_to_hex(head), remotes);
 588                free_commit_list(common);
 589                free_commit_list(remotes);
 590        }
 591
 592        /*
 593         * If the merge was clean or if it failed due to conflict, we write
 594         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 595         * However, if the merge did not even start, then we don't want to
 596         * write it at all.
 597         */
 598        if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1) &&
 599            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
 600                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 601                res = -1;
 602        if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
 603            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
 604                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 605                res = -1;
 606
 607        if (res) {
 608                error(opts->action == REPLAY_REVERT
 609                      ? _("could not revert %s... %s")
 610                      : _("could not apply %s... %s"),
 611                      find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV),
 612                      msg.subject);
 613                print_advice(res == 1, opts);
 614                rerere(opts->allow_rerere_auto);
 615                goto leave;
 616        }
 617
 618        allow = allow_empty(opts, commit);
 619        if (allow < 0) {
 620                res = allow;
 621                goto leave;
 622        }
 623        if (!opts->no_commit)
 624                res = run_git_commit(git_path_merge_msg(), opts, allow);
 625
 626leave:
 627        free_message(commit, &msg);
 628
 629        return res;
 630}
 631
 632static int prepare_revs(struct replay_opts *opts)
 633{
 634        /*
 635         * picking (but not reverting) ranges (but not individual revisions)
 636         * should be done in reverse
 637         */
 638        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
 639                opts->revs->reverse ^= 1;
 640
 641        if (prepare_revision_walk(opts->revs))
 642                return error(_("revision walk setup failed"));
 643
 644        if (!opts->revs->commits)
 645                return error(_("empty commit set passed"));
 646        return 0;
 647}
 648
 649static int read_and_refresh_cache(struct replay_opts *opts)
 650{
 651        static struct lock_file index_lock;
 652        int index_fd = hold_locked_index(&index_lock, 0);
 653        if (read_index_preload(&the_index, NULL) < 0) {
 654                rollback_lock_file(&index_lock);
 655                return error(_("git %s: failed to read the index"),
 656                        action_name(opts));
 657        }
 658        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 659        if (the_index.cache_changed && index_fd >= 0) {
 660                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
 661                        rollback_lock_file(&index_lock);
 662                        return error(_("git %s: failed to refresh the index"),
 663                                action_name(opts));
 664                }
 665        }
 666        rollback_lock_file(&index_lock);
 667        return 0;
 668}
 669
 670static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 671                struct replay_opts *opts)
 672{
 673        struct commit_list *cur = NULL;
 674        const char *sha1_abbrev = NULL;
 675        const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
 676        const char *subject;
 677        int subject_len;
 678
 679        for (cur = todo_list; cur; cur = cur->next) {
 680                const char *commit_buffer = get_commit_buffer(cur->item, NULL);
 681                sha1_abbrev = find_unique_abbrev(cur->item->object.oid.hash, DEFAULT_ABBREV);
 682                subject_len = find_commit_subject(commit_buffer, &subject);
 683                strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
 684                        subject_len, subject);
 685                unuse_commit_buffer(cur->item, commit_buffer);
 686        }
 687        return 0;
 688}
 689
 690static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
 691{
 692        unsigned char commit_sha1[20];
 693        enum replay_action action;
 694        char *end_of_object_name;
 695        int saved, status, padding;
 696
 697        if (starts_with(bol, "pick")) {
 698                action = REPLAY_PICK;
 699                bol += strlen("pick");
 700        } else if (starts_with(bol, "revert")) {
 701                action = REPLAY_REVERT;
 702                bol += strlen("revert");
 703        } else
 704                return NULL;
 705
 706        /* Eat up extra spaces/ tabs before object name */
 707        padding = strspn(bol, " \t");
 708        if (!padding)
 709                return NULL;
 710        bol += padding;
 711
 712        end_of_object_name = bol + strcspn(bol, " \t\n");
 713        saved = *end_of_object_name;
 714        *end_of_object_name = '\0';
 715        status = get_sha1(bol, commit_sha1);
 716        *end_of_object_name = saved;
 717
 718        /*
 719         * Verify that the action matches up with the one in
 720         * opts; we don't support arbitrary instructions
 721         */
 722        if (action != opts->action) {
 723                if (action == REPLAY_REVERT)
 724                      error((opts->action == REPLAY_REVERT)
 725                            ? _("Cannot revert during another revert.")
 726                            : _("Cannot revert during a cherry-pick."));
 727                else
 728                      error((opts->action == REPLAY_REVERT)
 729                            ? _("Cannot cherry-pick during a revert.")
 730                            : _("Cannot cherry-pick during another cherry-pick."));
 731                return NULL;
 732        }
 733
 734        if (status < 0)
 735                return NULL;
 736
 737        return lookup_commit_reference(commit_sha1);
 738}
 739
 740static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
 741                        struct replay_opts *opts)
 742{
 743        struct commit_list **next = todo_list;
 744        struct commit *commit;
 745        char *p = buf;
 746        int i;
 747
 748        for (i = 1; *p; i++) {
 749                char *eol = strchrnul(p, '\n');
 750                commit = parse_insn_line(p, eol, opts);
 751                if (!commit)
 752                        return error(_("Could not parse line %d."), i);
 753                next = commit_list_append(commit, next);
 754                p = *eol ? eol + 1 : eol;
 755        }
 756        if (!*todo_list)
 757                return error(_("No commits parsed."));
 758        return 0;
 759}
 760
 761static int read_populate_todo(struct commit_list **todo_list,
 762                        struct replay_opts *opts)
 763{
 764        struct strbuf buf = STRBUF_INIT;
 765        int fd, res;
 766
 767        fd = open(git_path_todo_file(), O_RDONLY);
 768        if (fd < 0)
 769                return error_errno(_("Could not open %s"),
 770                                   git_path_todo_file());
 771        if (strbuf_read(&buf, fd, 0) < 0) {
 772                close(fd);
 773                strbuf_release(&buf);
 774                return error(_("Could not read %s."), git_path_todo_file());
 775        }
 776        close(fd);
 777
 778        res = parse_insn_buffer(buf.buf, todo_list, opts);
 779        strbuf_release(&buf);
 780        if (res)
 781                return error(_("Unusable instruction sheet: %s"),
 782                        git_path_todo_file());
 783        return 0;
 784}
 785
 786static int populate_opts_cb(const char *key, const char *value, void *data)
 787{
 788        struct replay_opts *opts = data;
 789        int error_flag = 1;
 790
 791        if (!value)
 792                error_flag = 0;
 793        else if (!strcmp(key, "options.no-commit"))
 794                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 795        else if (!strcmp(key, "options.edit"))
 796                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 797        else if (!strcmp(key, "options.signoff"))
 798                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 799        else if (!strcmp(key, "options.record-origin"))
 800                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 801        else if (!strcmp(key, "options.allow-ff"))
 802                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 803        else if (!strcmp(key, "options.mainline"))
 804                opts->mainline = git_config_int(key, value);
 805        else if (!strcmp(key, "options.strategy"))
 806                git_config_string(&opts->strategy, key, value);
 807        else if (!strcmp(key, "options.gpg-sign"))
 808                git_config_string(&opts->gpg_sign, key, value);
 809        else if (!strcmp(key, "options.strategy-option")) {
 810                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 811                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 812        } else
 813                return error(_("Invalid key: %s"), key);
 814
 815        if (!error_flag)
 816                return error(_("Invalid value for %s: %s"), key, value);
 817
 818        return 0;
 819}
 820
 821static int read_populate_opts(struct replay_opts *opts)
 822{
 823        if (!file_exists(git_path_opts_file()))
 824                return 0;
 825        /*
 826         * The function git_parse_source(), called from git_config_from_file(),
 827         * may die() in case of a syntactically incorrect file. We do not care
 828         * about this case, though, because we wrote that file ourselves, so we
 829         * are pretty certain that it is syntactically correct.
 830         */
 831        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
 832                return error(_("Malformed options sheet: %s"),
 833                        git_path_opts_file());
 834        return 0;
 835}
 836
 837static int walk_revs_populate_todo(struct commit_list **todo_list,
 838                                struct replay_opts *opts)
 839{
 840        struct commit *commit;
 841        struct commit_list **next;
 842
 843        if (prepare_revs(opts))
 844                return -1;
 845
 846        next = todo_list;
 847        while ((commit = get_revision(opts->revs)))
 848                next = commit_list_append(commit, next);
 849        return 0;
 850}
 851
 852static int create_seq_dir(void)
 853{
 854        if (file_exists(git_path_seq_dir())) {
 855                error(_("a cherry-pick or revert is already in progress"));
 856                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
 857                return -1;
 858        }
 859        else if (mkdir(git_path_seq_dir(), 0777) < 0)
 860                return error_errno(_("Could not create sequencer directory %s"),
 861                                   git_path_seq_dir());
 862        return 0;
 863}
 864
 865static int save_head(const char *head)
 866{
 867        static struct lock_file head_lock;
 868        struct strbuf buf = STRBUF_INIT;
 869        int fd;
 870
 871        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
 872        if (fd < 0) {
 873                rollback_lock_file(&head_lock);
 874                return error_errno(_("Could not lock HEAD"));
 875        }
 876        strbuf_addf(&buf, "%s\n", head);
 877        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 878                rollback_lock_file(&head_lock);
 879                return error_errno(_("Could not write to %s"),
 880                                   git_path_head_file());
 881        }
 882        if (commit_lock_file(&head_lock) < 0) {
 883                rollback_lock_file(&head_lock);
 884                return error(_("Error wrapping up %s."), git_path_head_file());
 885        }
 886        return 0;
 887}
 888
 889static int reset_for_rollback(const unsigned char *sha1)
 890{
 891        const char *argv[4];    /* reset --merge <arg> + NULL */
 892        argv[0] = "reset";
 893        argv[1] = "--merge";
 894        argv[2] = sha1_to_hex(sha1);
 895        argv[3] = NULL;
 896        return run_command_v_opt(argv, RUN_GIT_CMD);
 897}
 898
 899static int rollback_single_pick(void)
 900{
 901        unsigned char head_sha1[20];
 902
 903        if (!file_exists(git_path_cherry_pick_head()) &&
 904            !file_exists(git_path_revert_head()))
 905                return error(_("no cherry-pick or revert in progress"));
 906        if (read_ref_full("HEAD", 0, head_sha1, NULL))
 907                return error(_("cannot resolve HEAD"));
 908        if (is_null_sha1(head_sha1))
 909                return error(_("cannot abort from a branch yet to be born"));
 910        return reset_for_rollback(head_sha1);
 911}
 912
 913static int sequencer_rollback(struct replay_opts *opts)
 914{
 915        FILE *f;
 916        unsigned char sha1[20];
 917        struct strbuf buf = STRBUF_INIT;
 918
 919        f = fopen(git_path_head_file(), "r");
 920        if (!f && errno == ENOENT) {
 921                /*
 922                 * There is no multiple-cherry-pick in progress.
 923                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
 924                 * a single-cherry-pick in progress, abort that.
 925                 */
 926                return rollback_single_pick();
 927        }
 928        if (!f)
 929                return error_errno(_("cannot open %s"), git_path_head_file());
 930        if (strbuf_getline_lf(&buf, f)) {
 931                error(_("cannot read %s: %s"), git_path_head_file(),
 932                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
 933                fclose(f);
 934                goto fail;
 935        }
 936        fclose(f);
 937        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
 938                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
 939                        git_path_head_file());
 940                goto fail;
 941        }
 942        if (is_null_sha1(sha1)) {
 943                error(_("cannot abort from a branch yet to be born"));
 944                goto fail;
 945        }
 946        if (reset_for_rollback(sha1))
 947                goto fail;
 948        remove_sequencer_state(opts);
 949        strbuf_release(&buf);
 950        return 0;
 951fail:
 952        strbuf_release(&buf);
 953        return -1;
 954}
 955
 956static int save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 957{
 958        static struct lock_file todo_lock;
 959        struct strbuf buf = STRBUF_INIT;
 960        int fd;
 961
 962        fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), 0);
 963        if (fd < 0)
 964                return error_errno(_("Could not lock '%s'"),
 965                                   git_path_todo_file());
 966        if (format_todo(&buf, todo_list, opts) < 0) {
 967                strbuf_release(&buf);
 968                return error(_("Could not format %s."), git_path_todo_file());
 969        }
 970        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 971                strbuf_release(&buf);
 972                return error_errno(_("Could not write to %s"),
 973                                   git_path_todo_file());
 974        }
 975        if (commit_lock_file(&todo_lock) < 0) {
 976                strbuf_release(&buf);
 977                return error(_("Error wrapping up %s."), git_path_todo_file());
 978        }
 979        strbuf_release(&buf);
 980        return 0;
 981}
 982
 983static int save_opts(struct replay_opts *opts)
 984{
 985        const char *opts_file = git_path_opts_file();
 986        int res = 0;
 987
 988        if (opts->no_commit)
 989                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
 990        if (opts->edit)
 991                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
 992        if (opts->signoff)
 993                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
 994        if (opts->record_origin)
 995                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
 996        if (opts->allow_ff)
 997                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
 998        if (opts->mainline) {
 999                struct strbuf buf = STRBUF_INIT;
1000                strbuf_addf(&buf, "%d", opts->mainline);
1001                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1002                strbuf_release(&buf);
1003        }
1004        if (opts->strategy)
1005                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1006        if (opts->gpg_sign)
1007                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1008        if (opts->xopts) {
1009                int i;
1010                for (i = 0; i < opts->xopts_nr; i++)
1011                        res |= git_config_set_multivar_in_file_gently(opts_file,
1012                                                        "options.strategy-option",
1013                                                        opts->xopts[i], "^$", 0);
1014        }
1015        return res;
1016}
1017
1018static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1019{
1020        struct commit_list *cur;
1021        int res;
1022
1023        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1024        if (opts->allow_ff)
1025                assert(!(opts->signoff || opts->no_commit ||
1026                                opts->record_origin || opts->edit));
1027        if (read_and_refresh_cache(opts))
1028                return -1;
1029
1030        for (cur = todo_list; cur; cur = cur->next) {
1031                if (save_todo(cur, opts))
1032                        return -1;
1033                res = do_pick_commit(cur->item, opts);
1034                if (res)
1035                        return res;
1036        }
1037
1038        /*
1039         * Sequence of picks finished successfully; cleanup by
1040         * removing the .git/sequencer directory
1041         */
1042        remove_sequencer_state(opts);
1043        return 0;
1044}
1045
1046static int continue_single_pick(void)
1047{
1048        const char *argv[] = { "commit", NULL };
1049
1050        if (!file_exists(git_path_cherry_pick_head()) &&
1051            !file_exists(git_path_revert_head()))
1052                return error(_("no cherry-pick or revert in progress"));
1053        return run_command_v_opt(argv, RUN_GIT_CMD);
1054}
1055
1056static int sequencer_continue(struct replay_opts *opts)
1057{
1058        struct commit_list *todo_list = NULL;
1059
1060        if (!file_exists(git_path_todo_file()))
1061                return continue_single_pick();
1062        if (read_populate_opts(opts) ||
1063                        read_populate_todo(&todo_list, opts))
1064                return -1;
1065
1066        /* Verify that the conflict has been resolved */
1067        if (file_exists(git_path_cherry_pick_head()) ||
1068            file_exists(git_path_revert_head())) {
1069                int ret = continue_single_pick();
1070                if (ret)
1071                        return ret;
1072        }
1073        if (index_differs_from("HEAD", 0))
1074                return error_dirty_index(opts);
1075        todo_list = todo_list->next;
1076        return pick_commits(todo_list, opts);
1077}
1078
1079static int single_pick(struct commit *cmit, struct replay_opts *opts)
1080{
1081        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1082        return do_pick_commit(cmit, opts);
1083}
1084
1085int sequencer_pick_revisions(struct replay_opts *opts)
1086{
1087        struct commit_list *todo_list = NULL;
1088        unsigned char sha1[20];
1089        int i;
1090
1091        if (opts->subcommand == REPLAY_NONE)
1092                assert(opts->revs);
1093
1094        if (read_and_refresh_cache(opts))
1095                return -1;
1096
1097        /*
1098         * Decide what to do depending on the arguments; a fresh
1099         * cherry-pick should be handled differently from an existing
1100         * one that is being continued
1101         */
1102        if (opts->subcommand == REPLAY_REMOVE_STATE) {
1103                remove_sequencer_state(opts);
1104                return 0;
1105        }
1106        if (opts->subcommand == REPLAY_ROLLBACK)
1107                return sequencer_rollback(opts);
1108        if (opts->subcommand == REPLAY_CONTINUE)
1109                return sequencer_continue(opts);
1110
1111        for (i = 0; i < opts->revs->pending.nr; i++) {
1112                unsigned char sha1[20];
1113                const char *name = opts->revs->pending.objects[i].name;
1114
1115                /* This happens when using --stdin. */
1116                if (!strlen(name))
1117                        continue;
1118
1119                if (!get_sha1(name, sha1)) {
1120                        if (!lookup_commit_reference_gently(sha1, 1)) {
1121                                enum object_type type = sha1_object_info(sha1, NULL);
1122                                return error(_("%s: can't cherry-pick a %s"),
1123                                        name, typename(type));
1124                        }
1125                } else
1126                        return error(_("%s: bad revision"), name);
1127        }
1128
1129        /*
1130         * If we were called as "git cherry-pick <commit>", just
1131         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1132         * REVERT_HEAD, and don't touch the sequencer state.
1133         * This means it is possible to cherry-pick in the middle
1134         * of a cherry-pick sequence.
1135         */
1136        if (opts->revs->cmdline.nr == 1 &&
1137            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1138            opts->revs->no_walk &&
1139            !opts->revs->cmdline.rev->flags) {
1140                struct commit *cmit;
1141                if (prepare_revision_walk(opts->revs))
1142                        return error(_("revision walk setup failed"));
1143                cmit = get_revision(opts->revs);
1144                if (!cmit || get_revision(opts->revs))
1145                        return error("BUG: expected exactly one commit from walk");
1146                return single_pick(cmit, opts);
1147        }
1148
1149        /*
1150         * Start a new cherry-pick/ revert sequence; but
1151         * first, make sure that an existing one isn't in
1152         * progress
1153         */
1154
1155        if (walk_revs_populate_todo(&todo_list, opts) ||
1156                        create_seq_dir() < 0)
1157                return -1;
1158        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1159                return error(_("Can't revert as initial commit"));
1160        if (save_head(sha1_to_hex(sha1)))
1161                return -1;
1162        if (save_opts(opts))
1163                return -1;
1164        return pick_commits(todo_list, opts);
1165}
1166
1167void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1168{
1169        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1170        struct strbuf sob = STRBUF_INIT;
1171        int has_footer;
1172
1173        strbuf_addstr(&sob, sign_off_header);
1174        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1175                                getenv("GIT_COMMITTER_EMAIL")));
1176        strbuf_addch(&sob, '\n');
1177
1178        /*
1179         * If the whole message buffer is equal to the sob, pretend that we
1180         * found a conforming footer with a matching sob
1181         */
1182        if (msgbuf->len - ignore_footer == sob.len &&
1183            !strncmp(msgbuf->buf, sob.buf, sob.len))
1184                has_footer = 3;
1185        else
1186                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1187
1188        if (!has_footer) {
1189                const char *append_newlines = NULL;
1190                size_t len = msgbuf->len - ignore_footer;
1191
1192                if (!len) {
1193                        /*
1194                         * The buffer is completely empty.  Leave foom for
1195                         * the title and body to be filled in by the user.
1196                         */
1197                        append_newlines = "\n\n";
1198                } else if (msgbuf->buf[len - 1] != '\n') {
1199                        /*
1200                         * Incomplete line.  Complete the line and add a
1201                         * blank one so that there is an empty line between
1202                         * the message body and the sob.
1203                         */
1204                        append_newlines = "\n\n";
1205                } else if (len == 1) {
1206                        /*
1207                         * Buffer contains a single newline.  Add another
1208                         * so that we leave room for the title and body.
1209                         */
1210                        append_newlines = "\n";
1211                } else if (msgbuf->buf[len - 2] != '\n') {
1212                        /*
1213                         * Buffer ends with a single newline.  Add another
1214                         * so that there is an empty line between the message
1215                         * body and the sob.
1216                         */
1217                        append_newlines = "\n";
1218                } /* else, the buffer already ends with two newlines. */
1219
1220                if (append_newlines)
1221                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1222                                append_newlines, strlen(append_newlines));
1223        }
1224
1225        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1226                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1227                                sob.buf, sob.len);
1228
1229        strbuf_release(&sob);
1230}