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