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