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