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