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