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